blob: 124bc60df10c75d8e8dfa68e8fedf035373bd745 [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.content;
Jason parksa3cdaa52011-01-13 14:15:43 -060018
Fred Quintanad9d2f112009-04-23 13:36:27 -070019import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070020import android.accounts.AccountAndUser;
Matthew Williamsfa774182013-06-18 15:44:11 -070021import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080022import android.content.ContentResolver;
23import android.content.Context;
24import android.content.ISyncStatusObserver;
25import android.content.PeriodicSync;
26import android.content.SyncInfo;
27import android.content.SyncStatusInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070030import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070032import android.os.Bundle;
33import android.os.Environment;
34import android.os.Handler;
35import android.os.Message;
36import android.os.Parcel;
37import android.os.RemoteCallbackList;
38import android.os.RemoteException;
Dianne Hackborn39606a02012-07-31 17:54:35 -070039import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.util.Log;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080041import android.util.Pair;
Dianne Hackborn231cc602009-04-27 17:10:36 -070042import android.util.SparseArray;
43import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080044
45import com.android.internal.annotations.VisibleForTesting;
46import com.android.internal.util.ArrayUtils;
47import com.android.internal.util.FastXmlSerializer;
48
49import org.xmlpull.v1.XmlPullParser;
50import org.xmlpull.v1.XmlPullParserException;
51import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052
Dianne Hackborn231cc602009-04-27 17:10:36 -070053import java.io.File;
54import java.io.FileInputStream;
55import java.io.FileOutputStream;
Matthew Williamsba352712013-08-13 15:53:31 -070056import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070058import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070060import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080061import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070062import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060063import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064
65/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070066 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070068 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 * @hide
70 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070071public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073 private static final String TAG = "SyncManager";
Matthew Williams28b1fc62013-08-29 13:41:15 -070074 private static final boolean DEBUG = false;
Matthew Williamsba352712013-08-13 15:53:31 -070075 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070076
Amith Yamasani04e0d262012-02-14 11:50:53 -080077 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
78 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070079 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080080 private static final String XML_ATTR_ENABLED = "enabled";
81 private static final String XML_ATTR_USER = "user";
82 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
83
Matthew Williamsfa774182013-06-18 15:44:11 -070084 /** Default time for a periodic sync. */
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080085 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
86
Matthew Williamsfa774182013-06-18 15:44:11 -070087 /** Percentage of period that is flex by default, if no flex is set. */
88 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
89
90 /** Lower bound on sync time from which we assign a default flex time. */
91 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
92
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080093 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070094 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095
Dianne Hackborn231cc602009-04-27 17:10:36 -070096 /** Enum value for a sync start event. */
97 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098
Dianne Hackborn231cc602009-04-27 17:10:36 -070099 /** Enum value for a sync stop event. */
100 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
Dianne Hackborn231cc602009-04-27 17:10:36 -0700102 // TODO: i18n -- grab these out of resources.
103 /** String names for the sync event types. */
104 public static final String[] EVENTS = { "START", "STOP" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
Dianne Hackborn231cc602009-04-27 17:10:36 -0700106 /** Enum value for a server-initiated sync. */
107 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
Dianne Hackborn231cc602009-04-27 17:10:36 -0700109 /** Enum value for a local-initiated sync. */
110 public static final int SOURCE_LOCAL = 1;
111 /**
112 * Enum value for a poll-based sync (e.g., upon connection to
113 * network)
114 */
115 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
Dianne Hackborn231cc602009-04-27 17:10:36 -0700117 /** Enum value for a user-initiated sync. */
118 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800120 /** Enum value for a periodic sync. */
121 public static final int SOURCE_PERIODIC = 4;
122
Fred Quintana307da1a2010-01-21 14:24:20 -0800123 public static final long NOT_IN_BACKOFF_MODE = -1;
124
Dianne Hackborn231cc602009-04-27 17:10:36 -0700125 // TODO: i18n -- grab these out of resources.
126 /** String names for the sync source types. */
127 public static final String[] SOURCES = { "SERVER",
128 "LOCAL",
129 "POLL",
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800130 "USER",
131 "PERIODIC" };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132
Dianne Hackborn231cc602009-04-27 17:10:36 -0700133 // The MESG column will contain one of these or one of the Error types.
134 public static final String MESG_SUCCESS = "success";
135 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700137 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700138
Dianne Hackborn231cc602009-04-27 17:10:36 -0700139 private static final int MSG_WRITE_STATUS = 1;
140 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700141
Dianne Hackborn231cc602009-04-27 17:10:36 -0700142 private static final int MSG_WRITE_STATISTICS = 2;
143 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700144
145 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700146
Fred Quintanac2e46912010-03-15 16:10:44 -0700147 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700148 private static final int ACCOUNTS_VERSION = 2;
149
150 private static HashMap<String, String> sAuthorityRenames;
151
152 static {
153 sAuthorityRenames = new HashMap<String, String>();
154 sAuthorityRenames.put("contacts", "com.android.contacts");
155 sAuthorityRenames.put("calendar", "com.android.calendar");
156 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700157
Dianne Hackborn231cc602009-04-27 17:10:36 -0700158 public static class PendingOperation {
Dianne Hackborn7a135592009-05-06 00:28:37 -0700159 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800160 final int userId;
Alon Albert57286f92012-10-09 14:21:38 -0700161 final int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700162 final int syncSource;
163 final String authority;
164 final Bundle extras; // note: read-only.
Matthew Williamsfa774182013-06-18 15:44:11 -0700165 final ComponentName serviceName;
Fred Quintana307da1a2010-01-21 14:24:20 -0800166 final boolean expedited;
Costin Manolache360e4542009-09-04 13:36:04 -0700167
Dianne Hackborn231cc602009-04-27 17:10:36 -0700168 int authorityId;
169 byte[] flatExtras;
Costin Manolache360e4542009-09-04 13:36:04 -0700170
Matthew Williamsfa774182013-06-18 15:44:11 -0700171 PendingOperation(Account account, int userId, int reason, int source,
Fred Quintana307da1a2010-01-21 14:24:20 -0800172 String authority, Bundle extras, boolean expedited) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700173 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800174 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700175 this.syncSource = source;
Alon Albert57286f92012-10-09 14:21:38 -0700176 this.reason = reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700177 this.authority = authority;
178 this.extras = extras != null ? new Bundle(extras) : extras;
Fred Quintana307da1a2010-01-21 14:24:20 -0800179 this.expedited = expedited;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700180 this.authorityId = -1;
Matthew Williamsfa774182013-06-18 15:44:11 -0700181 this.serviceName = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700182 }
183
184 PendingOperation(PendingOperation other) {
185 this.account = other.account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800186 this.userId = other.userId;
Alon Albert57286f92012-10-09 14:21:38 -0700187 this.reason = other.reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700188 this.syncSource = other.syncSource;
189 this.authority = other.authority;
190 this.extras = other.extras;
191 this.authorityId = other.authorityId;
Fred Quintana307da1a2010-01-21 14:24:20 -0800192 this.expedited = other.expedited;
Matthew Williamsfa774182013-06-18 15:44:11 -0700193 this.serviceName = other.serviceName;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 }
Costin Manolache360e4542009-09-04 13:36:04 -0700196
Dianne Hackborn231cc602009-04-27 17:10:36 -0700197 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800198 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700199 final HashMap<String, AuthorityInfo> authorities =
200 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700201
Amith Yamasani04e0d262012-02-14 11:50:53 -0800202 AccountInfo(AccountAndUser accountAndUser) {
203 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700204 }
205 }
Costin Manolache360e4542009-09-04 13:36:04 -0700206
Dianne Hackborn231cc602009-04-27 17:10:36 -0700207 public static class AuthorityInfo {
Matthew Williamsfa774182013-06-18 15:44:11 -0700208 final ComponentName service;
Dianne Hackborn7a135592009-05-06 00:28:37 -0700209 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800210 final int userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700211 final String authority;
212 final int ident;
213 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700214 int syncable;
Fred Quintana307da1a2010-01-21 14:24:20 -0800215 long backoffTime;
216 long backoffDelay;
217 long delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700218 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700219
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700220 /**
221 * Copy constructor for making deep-ish copies. Only the bundles stored
222 * in periodic syncs can make unexpected changes.
223 *
224 * @param toCopy AuthorityInfo to be copied.
225 */
226 AuthorityInfo(AuthorityInfo toCopy) {
227 account = toCopy.account;
228 userId = toCopy.userId;
229 authority = toCopy.authority;
Matthew Williamsfa774182013-06-18 15:44:11 -0700230 service = toCopy.service;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700231 ident = toCopy.ident;
232 enabled = toCopy.enabled;
233 syncable = toCopy.syncable;
234 backoffTime = toCopy.backoffTime;
235 backoffDelay = toCopy.backoffDelay;
236 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700237 periodicSyncs = new ArrayList<PeriodicSync>();
238 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700239 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700240 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700241 }
242 }
243
Matthew Williamsfa774182013-06-18 15:44:11 -0700244 /**
245 * Create an authority with one periodic sync scheduled with an empty bundle and syncing
246 * every day. An empty bundle is considered equal to any other bundle see
247 * {@link PeriodicSync.syncExtrasEquals}.
248 * @param account Account that this authority syncs.
249 * @param userId which user this sync is registered for.
250 * @param userId user for which this authority is registered.
251 * @param ident id of this authority.
252 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800253 AuthorityInfo(Account account, int userId, String authority, int ident) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700254 this.account = account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800255 this.userId = userId;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700256 this.authority = authority;
Matthew Williamsfa774182013-06-18 15:44:11 -0700257 this.service = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700258 this.ident = ident;
Joe Onorato8294fad2009-07-15 16:08:44 -0700259 enabled = SYNC_ENABLED_DEFAULT;
Fred Quintana4a6679b2009-08-17 13:05:39 -0700260 syncable = -1; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800261 backoffTime = -1; // if < 0 then we aren't in backoff mode
262 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Matthew Williamsfa774182013-06-18 15:44:11 -0700263 periodicSyncs = new ArrayList<PeriodicSync>();
264 // Old version adds one periodic sync a day.
265 periodicSyncs.add(new PeriodicSync(account, authority,
266 new Bundle(),
267 DEFAULT_POLL_FREQUENCY_SECONDS,
268 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS)));
269 }
270
271 /**
272 * Create an authority with one periodic sync scheduled with an empty bundle and syncing
273 * every day using a sync service.
274 * @param cname sync service identifier.
275 * @param userId user for which this authority is registered.
276 * @param ident id of this authority.
277 */
278 AuthorityInfo(ComponentName cname, int userId, int ident) {
279 this.account = null;
280 this.userId = userId;
281 this.authority = null;
282 this.service = cname;
283 this.ident = ident;
284 // Sync service is always enabled.
285 enabled = true;
286 syncable = -1; // default to "unknown"
287 backoffTime = -1; // if < 0 then we aren't in backoff mode
288 backoffDelay = -1; // if < 0 then we aren't in backoff mode
289 periodicSyncs = new ArrayList<PeriodicSync>();
290 periodicSyncs.add(new PeriodicSync(account, authority,
291 new Bundle(),
292 DEFAULT_POLL_FREQUENCY_SECONDS,
293 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS)));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700294 }
295 }
Costin Manolache360e4542009-09-04 13:36:04 -0700296
Dianne Hackborn231cc602009-04-27 17:10:36 -0700297 public static class SyncHistoryItem {
298 int authorityId;
299 int historyId;
300 long eventTime;
301 long elapsedTime;
302 int source;
303 int event;
304 long upstreamActivity;
305 long downstreamActivity;
306 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700307 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700308 Bundle extras;
309 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700310 }
Costin Manolache360e4542009-09-04 13:36:04 -0700311
Dianne Hackborn231cc602009-04-27 17:10:36 -0700312 public static class DayStats {
313 public final int day;
314 public int successCount;
315 public long successTime;
316 public int failureCount;
317 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700318
Dianne Hackborn231cc602009-04-27 17:10:36 -0700319 public DayStats(int day) {
320 this.day = day;
321 }
322 }
Costin Manolache360e4542009-09-04 13:36:04 -0700323
Amith Yamasani04e0d262012-02-14 11:50:53 -0800324 interface OnSyncRequestListener {
325 /**
326 * Called when a sync is needed on an account(s) due to some change in state.
327 * @param account
328 * @param userId
Alon Albert57286f92012-10-09 14:21:38 -0700329 * @param reason
Amith Yamasani04e0d262012-02-14 11:50:53 -0800330 * @param authority
331 * @param extras
332 */
Alon Albert57286f92012-10-09 14:21:38 -0700333 public void onSyncRequest(Account account, int userId, int reason, String authority,
334 Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800335 }
336
Dianne Hackborn231cc602009-04-27 17:10:36 -0700337 // Primary list of all syncable authorities. Also our global lock.
338 private final SparseArray<AuthorityInfo> mAuthorities =
339 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700340
Amith Yamasani04e0d262012-02-14 11:50:53 -0800341 private final HashMap<AccountAndUser, AccountInfo> mAccounts
342 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343
Dianne Hackborn231cc602009-04-27 17:10:36 -0700344 private final ArrayList<PendingOperation> mPendingOperations =
345 new ArrayList<PendingOperation>();
Costin Manolache360e4542009-09-04 13:36:04 -0700346
Amith Yamasani04e0d262012-02-14 11:50:53 -0800347 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
348 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700349
Dianne Hackborn231cc602009-04-27 17:10:36 -0700350 private final SparseArray<SyncStatusInfo> mSyncStatus =
351 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700352
Dianne Hackborn231cc602009-04-27 17:10:36 -0700353 private final ArrayList<SyncHistoryItem> mSyncHistory =
354 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700355
Dianne Hackborn231cc602009-04-27 17:10:36 -0700356 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
357 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700358
Matthew Williamsfa774182013-06-18 15:44:11 -0700359 /** Reverse mapping for component name -> <userid -> authority id>. */
360 private final HashMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
361 new HashMap<ComponentName, SparseArray<AuthorityInfo>>();
362
Fred Quintana77c560f2010-03-29 22:20:26 -0700363 private int mNextAuthorityId = 0;
364
Dianne Hackborn231cc602009-04-27 17:10:36 -0700365 // We keep 4 weeks of stats.
366 private final DayStats[] mDayStats = new DayStats[7*4];
367 private final Calendar mCal;
368 private int mYear;
369 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700370
Dianne Hackborn231cc602009-04-27 17:10:36 -0700371 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800372
Dianne Hackborn231cc602009-04-27 17:10:36 -0700373 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700374
Ashish Sharma69d95de2012-04-11 17:27:24 -0700375 private int mSyncRandomOffset;
376
Dianne Hackborn231cc602009-04-27 17:10:36 -0700377 /**
378 * This file contains the core engine state: all accounts and the
379 * settings for them. It must never be lost, and should be changed
380 * infrequently, so it is stored as an XML file.
381 */
382 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700383
Dianne Hackborn231cc602009-04-27 17:10:36 -0700384 /**
385 * This file contains the current sync status. We would like to retain
386 * it across boots, but its loss is not the end of the world, so we store
387 * this information as binary data.
388 */
389 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700390
Dianne Hackborn231cc602009-04-27 17:10:36 -0700391 /**
392 * This file contains sync statistics. This is purely debugging information
393 * so is written infrequently and can be thrown away at any time.
394 */
395 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700396
Dianne Hackborn231cc602009-04-27 17:10:36 -0700397 /**
398 * This file contains the pending sync operations. It is a binary file,
399 * which must be updated every time an operation is added or removed,
400 * so we have special handling of it.
401 */
402 private final AtomicFile mPendingFile;
403 private static final int PENDING_FINISH_TO_WRITE = 4;
404 private int mNumPendingFinished = 0;
Costin Manolache360e4542009-09-04 13:36:04 -0700405
Dianne Hackborn231cc602009-04-27 17:10:36 -0700406 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800407 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800408 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800409
410 private OnSyncRequestListener mSyncRequestListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700411
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800412 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700415
Dianne Hackborn231cc602009-04-27 17:10:36 -0700416 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700417
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800418 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
419 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
420
Dianne Hackborn231cc602009-04-27 17:10:36 -0700421 File systemDir = new File(dataDir, "system");
422 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800423 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700424
425 maybeDeleteLegacyPendingInfoLocked(syncDir);
426
Dianne Hackborn231cc602009-04-27 17:10:36 -0700427 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
428 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Matthew Williamsba352712013-08-13 15:53:31 -0700429 mPendingFile = new AtomicFile(new File(syncDir, "pending.xml"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700430 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700431
Dianne Hackborn231cc602009-04-27 17:10:36 -0700432 readAccountInfoLocked();
433 readStatusLocked();
434 readPendingOperationsLocked();
435 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700436 readAndDeleteLegacyAccountInfoLocked();
437 writeAccountInfoLocked();
438 writeStatusLocked();
439 writePendingOperationsLocked();
440 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 }
442
443 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800444 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 }
446
447 public static void init(Context context) {
448 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800449 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800451 // This call will return the correct directory whether Encrypted File Systems is
452 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600453 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800454 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 }
456
457 public static SyncStorageEngine getSingleton() {
458 if (sSyncStorageEngine == null) {
459 throw new IllegalStateException("not initialized");
460 }
461 return sSyncStorageEngine;
462 }
463
Amith Yamasani04e0d262012-02-14 11:50:53 -0800464 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
465 if (mSyncRequestListener == null) {
466 mSyncRequestListener = listener;
467 }
468 }
469
Dianne Hackborn231cc602009-04-27 17:10:36 -0700470 @Override public void handleMessage(Message msg) {
471 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700472 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700473 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700474 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700475 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700476 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700477 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 }
479 }
480 }
Costin Manolache360e4542009-09-04 13:36:04 -0700481
Ashish Sharma69d95de2012-04-11 17:27:24 -0700482 public int getSyncRandomOffset() {
483 return mSyncRandomOffset;
484 }
485
Dianne Hackborn231cc602009-04-27 17:10:36 -0700486 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
487 synchronized (mAuthorities) {
488 mChangeListeners.register(callback, mask);
489 }
490 }
Costin Manolache360e4542009-09-04 13:36:04 -0700491
Dianne Hackborn231cc602009-04-27 17:10:36 -0700492 public void removeStatusChangeListener(ISyncStatusObserver callback) {
493 synchronized (mAuthorities) {
494 mChangeListeners.unregister(callback);
495 }
496 }
Costin Manolache360e4542009-09-04 13:36:04 -0700497
Matthew Williamsfa774182013-06-18 15:44:11 -0700498 /**
499 * Figure out a reasonable flex time for cases where none is provided (old api calls).
500 * @param syncTimeSeconds requested sync time from now.
501 * @return amount of seconds before syncTimeSeconds that the sync can occur.
502 * I.e.
503 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
504 * The flex time is capped at a percentage of the {@link DEFAULT_POLL_FREQUENCY_SECONDS}.
505 */
506 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
507 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
508 // Small enough sync request time that we don't add flex time - developer probably
509 // wants to wait for an operation to occur before syncing so we honour the
510 // request time.
511 return 0L;
512 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
513 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
514 } else {
515 // Large enough sync request time that we cap the flex time.
516 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
517 }
518 }
519
Dianne Hackborn231cc602009-04-27 17:10:36 -0700520 private void reportChange(int which) {
521 ArrayList<ISyncStatusObserver> reports = null;
522 synchronized (mAuthorities) {
523 int i = mChangeListeners.beginBroadcast();
524 while (i > 0) {
525 i--;
526 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
527 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 continue;
529 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700530 if (reports == null) {
531 reports = new ArrayList<ISyncStatusObserver>(i);
532 }
533 reports.add(mChangeListeners.getBroadcastItem(i));
534 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700535 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700536 }
Costin Manolache360e4542009-09-04 13:36:04 -0700537
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800538 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700539 Log.v(TAG, "reportChange " + which + " to: " + reports);
540 }
Costin Manolache360e4542009-09-04 13:36:04 -0700541
Dianne Hackborn231cc602009-04-27 17:10:36 -0700542 if (reports != null) {
543 int i = reports.size();
544 while (i > 0) {
545 i--;
546 try {
547 reports.get(i).onStatusChanged(which);
548 } catch (RemoteException e) {
549 // The remote callback list will take care of this for us.
550 }
551 }
552 }
553 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700554
Amith Yamasani04e0d262012-02-14 11:50:53 -0800555 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700556 synchronized (mAuthorities) {
557 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800558 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintanaac9385e2009-06-22 18:00:59 -0700559 "getSyncAutomatically");
560 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700561 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700562
Dianne Hackborn231cc602009-04-27 17:10:36 -0700563 int i = mAuthorities.size();
564 while (i > 0) {
565 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700566 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700567 if (authority.authority.equals(providerName)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800568 && authority.userId == userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700569 && authority.enabled) {
570 return true;
571 }
572 }
573 return false;
574 }
575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576
Amith Yamasani04e0d262012-02-14 11:50:53 -0800577 public void setSyncAutomatically(Account account, int userId, String providerName,
578 boolean sync) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800579 if (DEBUG) {
580 Log.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
581 + ", user " + userId + " -> " + sync);
582 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700583 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800584 AuthorityInfo authority = getOrCreateAuthorityLocked(account, userId, providerName, -1,
585 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700586 if (authority.enabled == sync) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800587 if (DEBUG) {
588 Log.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
589 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700590 return;
591 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700592 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700593 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700595
Fred Quintana77c560f2010-03-29 22:20:26 -0700596 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700597 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
598 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700599 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700600 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 }
602
Amith Yamasani04e0d262012-02-14 11:50:53 -0800603 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700604 synchronized (mAuthorities) {
605 if (account != null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800606 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
Fred Quintana5e787c42009-08-16 23:13:53 -0700607 "getIsSyncable");
608 if (authority == null) {
609 return -1;
610 }
611 return authority.syncable;
612 }
613
614 int i = mAuthorities.size();
615 while (i > 0) {
616 i--;
Costin Manolache360e4542009-09-04 13:36:04 -0700617 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintana5e787c42009-08-16 23:13:53 -0700618 if (authority.authority.equals(providerName)) {
619 return authority.syncable;
620 }
621 }
622 return -1;
623 }
624 }
625
Amith Yamasani04e0d262012-02-14 11:50:53 -0800626 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Fred Quintanab763ab22009-08-18 18:07:30 -0700627 if (syncable > 1) {
628 syncable = 1;
629 } else if (syncable < -1) {
630 syncable = -1;
631 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800632 if (DEBUG) {
633 Log.d(TAG, "setIsSyncable: " + account + ", provider " + providerName
634 + ", user " + userId + " -> " + syncable);
635 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700636 synchronized (mAuthorities) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700637 AuthorityInfo authority =
638 getOrCreateAuthorityLocked(account, userId, providerName, -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700639 if (authority.syncable == syncable) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800640 if (DEBUG) {
641 Log.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
642 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700643 return;
644 }
Fred Quintana5e787c42009-08-16 23:13:53 -0700645 authority.syncable = syncable;
646 writeAccountInfoLocked();
647 }
648
Fred Quintana77c560f2010-03-29 22:20:26 -0700649 if (syncable > 0) {
Alon Albert57286f92012-10-09 14:21:38 -0700650 requestSync(account, userId, SyncOperation.REASON_IS_SYNCABLE, providerName,
651 new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700652 }
653 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
654 }
655
Amith Yamasani04e0d262012-02-14 11:50:53 -0800656 public Pair<Long, Long> getBackoff(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800657 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800658 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
659 "getBackoff");
Fred Quintana307da1a2010-01-21 14:24:20 -0800660 if (authority == null || authority.backoffTime < 0) {
661 return null;
662 }
663 return Pair.create(authority.backoffTime, authority.backoffDelay);
664 }
665 }
666
Amith Yamasani04e0d262012-02-14 11:50:53 -0800667 public void setBackoff(Account account, int userId, String providerName,
Fred Quintana307da1a2010-01-21 14:24:20 -0800668 long nextSyncTime, long nextDelay) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800669 if (DEBUG) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800670 Log.v(TAG, "setBackoff: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800671 + ", user " + userId
Fred Quintana307da1a2010-01-21 14:24:20 -0800672 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
673 }
674 boolean changed = false;
675 synchronized (mAuthorities) {
676 if (account == null || providerName == null) {
677 for (AccountInfo accountInfo : mAccounts.values()) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800678 if (account != null && !account.equals(accountInfo.accountAndUser.account)
679 && userId != accountInfo.accountAndUser.userId) {
680 continue;
681 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800682 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
Matthew Williamsba352712013-08-13 15:53:31 -0700683 if (providerName != null
684 && !providerName.equals(authorityInfo.authority)) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800685 continue;
686 }
687 if (authorityInfo.backoffTime != nextSyncTime
688 || authorityInfo.backoffDelay != nextDelay) {
689 authorityInfo.backoffTime = nextSyncTime;
690 authorityInfo.backoffDelay = nextDelay;
691 changed = true;
692 }
693 }
694 }
695 } else {
696 AuthorityInfo authority =
Amith Yamasani04e0d262012-02-14 11:50:53 -0800697 getOrCreateAuthorityLocked(account, userId, providerName, -1 /* ident */,
698 true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800699 if (authority.backoffTime == nextSyncTime && authority.backoffDelay == nextDelay) {
700 return;
701 }
702 authority.backoffTime = nextSyncTime;
703 authority.backoffDelay = nextDelay;
704 changed = true;
705 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800706 }
707
708 if (changed) {
709 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
710 }
711 }
712
Matthew Williamsed37b932013-09-12 14:30:09 -0700713 /**
714 * Callers of this function need to hold a lock for syncQueue object passed in. Bear in mind
715 * this function grabs the lock for {@link #mAuthorities}
716 * @param syncQueue queue containing pending sync operations.
717 */
718 public void clearAllBackoffsLocked(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800719 boolean changed = false;
720 synchronized (mAuthorities) {
Matthew Williamsed37b932013-09-12 14:30:09 -0700721 for (AccountInfo accountInfo : mAccounts.values()) {
722 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
723 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
724 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
725 if (DEBUG) {
726 Log.v(TAG, "clearAllBackoffs:"
727 + " authority:" + authorityInfo.authority
728 + " account:" + accountInfo.accountAndUser.account.name
729 + " user:" + accountInfo.accountAndUser.userId
730 + " backoffTime was: " + authorityInfo.backoffTime
731 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800732 }
Matthew Williamsed37b932013-09-12 14:30:09 -0700733 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
734 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
735 syncQueue.onBackoffChanged(accountInfo.accountAndUser.account,
736 accountInfo.accountAndUser.userId, authorityInfo.authority, 0);
737 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800738 }
739 }
740 }
741 }
742
743 if (changed) {
744 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
745 }
746 }
747
Amith Yamasani04e0d262012-02-14 11:50:53 -0800748 public void setDelayUntilTime(Account account, int userId, String providerName,
749 long delayUntil) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800750 if (DEBUG) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800751 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800752 + ", user " + userId + " -> delayUntil " + delayUntil);
Fred Quintana307da1a2010-01-21 14:24:20 -0800753 }
754 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800755 AuthorityInfo authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -0800756 account, userId, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800757 if (authority.delayUntil == delayUntil) {
758 return;
759 }
760 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800761 }
762
763 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
764 }
765
Amith Yamasani04e0d262012-02-14 11:50:53 -0800766 public long getDelayUntilTime(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800767 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800768 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
769 "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800770 if (authority == null) {
771 return 0;
772 }
773 return authority.delayUntil;
774 }
775 }
776
Matthew Williamsfa774182013-06-18 15:44:11 -0700777 private void updateOrRemovePeriodicSync(PeriodicSync toUpdate, int userId, boolean add) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800778 if (DEBUG) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700779 Log.v(TAG, "addOrRemovePeriodicSync: " + toUpdate.account + ", user " + userId
780 + ", provider " + toUpdate.authority
781 + " -> period " + toUpdate.period + ", extras " + toUpdate.extras);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800782 }
783 synchronized (mAuthorities) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700784 if (toUpdate.period <= 0 && add) {
Matthew Williamsba352712013-08-13 15:53:31 -0700785 Log.e(TAG, "period < 0, should never happen in updateOrRemovePeriodicSync: add-"
786 + add);
Matthew Williamsfa774182013-06-18 15:44:11 -0700787 }
788 if (toUpdate.extras == null) {
Matthew Williamsba352712013-08-13 15:53:31 -0700789 Log.e(TAG, "null extras, should never happen in updateOrRemovePeriodicSync: add-"
790 + add);
Matthew Williamsfa774182013-06-18 15:44:11 -0700791 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700792 try {
793 AuthorityInfo authority =
Matthew Williamsfa774182013-06-18 15:44:11 -0700794 getOrCreateAuthorityLocked(toUpdate.account, userId, toUpdate.authority,
795 -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700796 if (add) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700797 // add this periodic sync if an equivalent periodic doesn't already exist.
Fred Quintana77c560f2010-03-29 22:20:26 -0700798 boolean alreadyPresent = false;
799 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700800 PeriodicSync syncInfo = authority.periodicSyncs.get(i);
801 if (PeriodicSync.syncExtrasEquals(
802 toUpdate.extras,
803 syncInfo.extras)) {
804 if (toUpdate.period == syncInfo.period &&
805 toUpdate.flexTime == syncInfo.flexTime) {
806 // Absolutely the same.
Fred Quintana77c560f2010-03-29 22:20:26 -0700807 return;
808 }
Matthew Williamsfa774182013-06-18 15:44:11 -0700809 authority.periodicSyncs.set(i, new PeriodicSync(toUpdate));
Fred Quintana77c560f2010-03-29 22:20:26 -0700810 alreadyPresent = true;
811 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800812 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700813 }
Matthew Williamsfa774182013-06-18 15:44:11 -0700814 // If we added an entry to the periodicSyncs array also add an entry to
815 // the periodic syncs status to correspond to it.
Fred Quintana77c560f2010-03-29 22:20:26 -0700816 if (!alreadyPresent) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700817 authority.periodicSyncs.add(new PeriodicSync(toUpdate));
Fred Quintana77c560f2010-03-29 22:20:26 -0700818 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Matthew Williamsba352712013-08-13 15:53:31 -0700819 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0L);
Fred Quintana77c560f2010-03-29 22:20:26 -0700820 }
821 } else {
Matthew Williamsfa774182013-06-18 15:44:11 -0700822 // Remove any periodic syncs that match the authority and extras.
Fred Quintana77c560f2010-03-29 22:20:26 -0700823 SyncStatusInfo status = mSyncStatus.get(authority.ident);
824 boolean changed = false;
Matthew Williamsfa774182013-06-18 15:44:11 -0700825 Iterator<PeriodicSync> iterator = authority.periodicSyncs.iterator();
Fred Quintana77c560f2010-03-29 22:20:26 -0700826 int i = 0;
827 while (iterator.hasNext()) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700828 PeriodicSync syncInfo = iterator.next();
829 if (PeriodicSync.syncExtrasEquals(syncInfo.extras, toUpdate.extras)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700830 iterator.remove();
831 changed = true;
Matthew Williamsfa774182013-06-18 15:44:11 -0700832 // If we removed an entry from the periodicSyncs array also
Fred Quintana77c560f2010-03-29 22:20:26 -0700833 // remove the corresponding entry from the status
834 if (status != null) {
835 status.removePeriodicSyncTime(i);
Matthew Williamsfa774182013-06-18 15:44:11 -0700836 } else {
Matthew Williamsba352712013-08-13 15:53:31 -0700837 Log.e(TAG, "Tried removing sync status on remove periodic sync but"
838 + "did not find it.");
Fred Quintana77c560f2010-03-29 22:20:26 -0700839 }
840 } else {
841 i++;
842 }
843 }
844 if (!changed) {
845 return;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800846 }
847 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700848 } finally {
849 writeAccountInfoLocked();
850 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800851 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800852 }
853
854 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
855 }
856
Matthew Williamsfa774182013-06-18 15:44:11 -0700857 public void addPeriodicSync(PeriodicSync toAdd, int userId) {
858 updateOrRemovePeriodicSync(toAdd, userId, true /* add */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800859 }
860
Matthew Williamsfa774182013-06-18 15:44:11 -0700861 public void removePeriodicSync(PeriodicSync toRemove, int userId) {
862 updateOrRemovePeriodicSync(toRemove, userId, false /* remove */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800863 }
864
Amith Yamasani04e0d262012-02-14 11:50:53 -0800865 public List<PeriodicSync> getPeriodicSyncs(Account account, int userId, String providerName) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800866 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
867 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800868 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
869 "getPeriodicSyncs");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800870 if (authority != null) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700871 for (PeriodicSync item : authority.periodicSyncs) {
872 // Copy and send out. Necessary for thread-safety although it's parceled.
873 syncs.add(new PeriodicSync(item));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800874 }
875 }
876 }
877 return syncs;
878 }
879
Amith Yamasani04e0d262012-02-14 11:50:53 -0800880 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700881 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800882 Boolean auto = mMasterSyncAutomatically.get(userId);
883 if (auto != null && (boolean) auto == flag) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700884 return;
885 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800886 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700887 writeAccountInfoLocked();
888 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700889 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700890 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
891 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700892 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700893 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800894 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896
Amith Yamasani04e0d262012-02-14 11:50:53 -0800897 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700898 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800899 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800900 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700901 }
902 }
Costin Manolache360e4542009-09-04 13:36:04 -0700903
Amith Yamasani04e0d262012-02-14 11:50:53 -0800904 public void removeAuthority(Account account, int userId, String authority) {
Fred Quintana7620f1a2010-03-16 15:58:44 -0700905 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800906 removeAuthorityLocked(account, userId, authority, true /* doWrite */);
Fred Quintana7620f1a2010-03-16 15:58:44 -0700907 }
908 }
909
Dianne Hackborn231cc602009-04-27 17:10:36 -0700910 public AuthorityInfo getAuthority(int authorityId) {
911 synchronized (mAuthorities) {
912 return mAuthorities.get(authorityId);
913 }
914 }
Costin Manolache360e4542009-09-04 13:36:04 -0700915
Dianne Hackborn231cc602009-04-27 17:10:36 -0700916 /**
917 * Returns true if there is currently a sync operation for the given
Fred Quintana918339a2010-10-05 14:00:39 -0700918 * account or authority actively being processed.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700919 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800920 public boolean isSyncActive(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700921 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800922 for (SyncInfo syncInfo : getCurrentSyncs(userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700923 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700924 if (ainfo != null && ainfo.account.equals(account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800925 && ainfo.authority.equals(authority)
926 && ainfo.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700927 return true;
928 }
929 }
930 }
Costin Manolache360e4542009-09-04 13:36:04 -0700931
Dianne Hackborn231cc602009-04-27 17:10:36 -0700932 return false;
933 }
Costin Manolache360e4542009-09-04 13:36:04 -0700934
Dianne Hackborn231cc602009-04-27 17:10:36 -0700935 public PendingOperation insertIntoPending(PendingOperation op) {
936 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800937 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700938 Log.v(TAG, "insertIntoPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800939 + " user=" + op.userId
940 + " auth=" + op.authority
941 + " src=" + op.syncSource
942 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700943 }
Costin Manolache360e4542009-09-04 13:36:04 -0700944
Amith Yamasani04e0d262012-02-14 11:50:53 -0800945 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account, op.userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700946 op.authority,
947 -1 /* desired identifier */,
948 true /* write accounts to storage */);
949 if (authority == null) {
950 return null;
951 }
Costin Manolache360e4542009-09-04 13:36:04 -0700952
Dianne Hackborn231cc602009-04-27 17:10:36 -0700953 op = new PendingOperation(op);
954 op.authorityId = authority.ident;
955 mPendingOperations.add(op);
Matthew Williamsba352712013-08-13 15:53:31 -0700956 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700957
Dianne Hackborn231cc602009-04-27 17:10:36 -0700958 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
959 status.pending = true;
960 }
Costin Manolache360e4542009-09-04 13:36:04 -0700961
Fred Quintanaac9385e2009-06-22 18:00:59 -0700962 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700963 return op;
964 }
965
Matthew Williamsfa774182013-06-18 15:44:11 -0700966 /**
967 * Remove from list of pending operations. If successful, search through list for matching
968 * authorities. If there are no more pending syncs for the same authority/account/userid,
969 * update the SyncStatusInfo for that authority(authority here is the internal representation
970 * of a 'sync operation'.
971 * @param op
972 * @return
973 */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700974 public boolean deleteFromPending(PendingOperation op) {
975 boolean res = false;
976 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800977 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700978 Log.v(TAG, "deleteFromPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800979 + " user=" + op.userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700980 + " auth=" + op.authority
981 + " src=" + op.syncSource
982 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700983 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700984 if (mPendingOperations.remove(op)) {
985 if (mPendingOperations.size() == 0
986 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
987 writePendingOperationsLocked();
988 mNumPendingFinished = 0;
989 } else {
990 mNumPendingFinished++;
991 }
Costin Manolache360e4542009-09-04 13:36:04 -0700992
Amith Yamasani04e0d262012-02-14 11:50:53 -0800993 AuthorityInfo authority = getAuthorityLocked(op.account, op.userId, op.authority,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700994 "deleteFromPending");
995 if (authority != null) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700996 if (DEBUG) Log.v(TAG, "removing - " + authority.toString());
Dianne Hackborn231cc602009-04-27 17:10:36 -0700997 final int N = mPendingOperations.size();
998 boolean morePending = false;
999 for (int i=0; i<N; i++) {
1000 PendingOperation cur = mPendingOperations.get(i);
1001 if (cur.account.equals(op.account)
Amith Yamasani04e0d262012-02-14 11:50:53 -08001002 && cur.authority.equals(op.authority)
1003 && cur.userId == op.userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001004 morePending = true;
1005 break;
1006 }
1007 }
Costin Manolache360e4542009-09-04 13:36:04 -07001008
Dianne Hackborn231cc602009-04-27 17:10:36 -07001009 if (!morePending) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001010 if (DEBUG) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001011 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1012 status.pending = false;
1013 }
1014 }
Costin Manolache360e4542009-09-04 13:36:04 -07001015
Dianne Hackborn231cc602009-04-27 17:10:36 -07001016 res = true;
1017 }
1018 }
Costin Manolache360e4542009-09-04 13:36:04 -07001019
Fred Quintanaac9385e2009-06-22 18:00:59 -07001020 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001021 return res;
1022 }
1023
Dianne Hackborn231cc602009-04-27 17:10:36 -07001024 /**
1025 * Return a copy of the current array of pending operations. The
1026 * PendingOperation objects are the real objects stored inside, so that
1027 * they can be used with deleteFromPending().
1028 */
1029 public ArrayList<PendingOperation> getPendingOperations() {
1030 synchronized (mAuthorities) {
1031 return new ArrayList<PendingOperation>(mPendingOperations);
1032 }
1033 }
Costin Manolache360e4542009-09-04 13:36:04 -07001034
Dianne Hackborn231cc602009-04-27 17:10:36 -07001035 /**
1036 * Return the number of currently pending operations.
1037 */
1038 public int getPendingOperationCount() {
1039 synchronized (mAuthorities) {
1040 return mPendingOperations.size();
1041 }
1042 }
Costin Manolache360e4542009-09-04 13:36:04 -07001043
Dianne Hackborn231cc602009-04-27 17:10:36 -07001044 /**
1045 * Called when the set of account has changed, given the new array of
1046 * active accounts.
1047 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001048 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001049 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001050 if (DEBUG) Log.v(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001051 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1052 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1053 while (accIt.hasNext()) {
1054 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001055 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
1056 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001057 // This account no longer exists...
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001058 if (DEBUG) {
1059 Log.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001060 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001061 for (AuthorityInfo auth : acc.authorities.values()) {
1062 removing.put(auth.ident, auth);
1063 }
1064 accIt.remove();
1065 }
1066 }
Costin Manolache360e4542009-09-04 13:36:04 -07001067
Dianne Hackborn231cc602009-04-27 17:10:36 -07001068 // Clean out all data structures.
1069 int i = removing.size();
1070 if (i > 0) {
1071 while (i > 0) {
1072 i--;
1073 int ident = removing.keyAt(i);
1074 mAuthorities.remove(ident);
1075 int j = mSyncStatus.size();
1076 while (j > 0) {
1077 j--;
1078 if (mSyncStatus.keyAt(j) == ident) {
1079 mSyncStatus.remove(mSyncStatus.keyAt(j));
1080 }
1081 }
1082 j = mSyncHistory.size();
1083 while (j > 0) {
1084 j--;
1085 if (mSyncHistory.get(j).authorityId == ident) {
1086 mSyncHistory.remove(j);
1087 }
1088 }
1089 }
1090 writeAccountInfoLocked();
1091 writeStatusLocked();
1092 writePendingOperationsLocked();
1093 writeStatisticsLocked();
1094 }
1095 }
1096 }
1097
1098 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001099 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1100 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001101 */
Fred Quintana918339a2010-10-05 14:00:39 -07001102 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1103 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001104 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001105 if (DEBUG) {
Fred Quintana918339a2010-10-05 14:00:39 -07001106 Log.v(TAG, "setActiveSync: account="
1107 + activeSyncContext.mSyncOperation.account
1108 + " auth=" + activeSyncContext.mSyncOperation.authority
1109 + " src=" + activeSyncContext.mSyncOperation.syncSource
1110 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001111 }
Fred Quintana918339a2010-10-05 14:00:39 -07001112 AuthorityInfo authority = getOrCreateAuthorityLocked(
1113 activeSyncContext.mSyncOperation.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001114 activeSyncContext.mSyncOperation.userId,
Fred Quintana918339a2010-10-05 14:00:39 -07001115 activeSyncContext.mSyncOperation.authority,
1116 -1 /* assign a new identifier if creating a new authority */,
1117 true /* write to storage if this results in a change */);
1118 syncInfo = new SyncInfo(authority.ident,
1119 authority.account, authority.authority,
1120 activeSyncContext.mStartTime);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001121 getCurrentSyncs(authority.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001122 }
Costin Manolache360e4542009-09-04 13:36:04 -07001123
Fred Quintana918339a2010-10-05 14:00:39 -07001124 reportActiveChange();
1125 return syncInfo;
1126 }
1127
1128 /**
1129 * Called to indicate that a previously active sync is no longer active.
1130 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001131 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001132 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001133 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001134 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1135 + " user=" + userId
1136 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001137 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001138 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001139 }
1140
1141 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001142 }
1143
1144 /**
1145 * To allow others to send active change reports, to poke clients.
1146 */
1147 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001148 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001149 }
Costin Manolache360e4542009-09-04 13:36:04 -07001150
Dianne Hackborn231cc602009-04-27 17:10:36 -07001151 /**
1152 * Note that sync has started for the given account and authority.
1153 */
Alon Albert57286f92012-10-09 14:21:38 -07001154 public long insertStartSyncEvent(Account accountName, int userId, int reason,
1155 String authorityName, long now, int source, boolean initialization, Bundle extras) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001156 long id;
1157 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001158 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001159 Log.v(TAG, "insertStartSyncEvent: account=" + accountName + "user=" + userId
Dianne Hackborn231cc602009-04-27 17:10:36 -07001160 + " auth=" + authorityName + " source=" + source);
Fred Quintana77c560f2010-03-29 22:20:26 -07001161 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001162 AuthorityInfo authority = getAuthorityLocked(accountName, userId, authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001163 "insertStartSyncEvent");
1164 if (authority == null) {
1165 return -1;
1166 }
1167 SyncHistoryItem item = new SyncHistoryItem();
Fred Quintanadc475562012-05-04 15:51:54 -07001168 item.initialization = initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001169 item.authorityId = authority.ident;
1170 item.historyId = mNextHistoryId++;
1171 if (mNextHistoryId < 0) mNextHistoryId = 0;
1172 item.eventTime = now;
1173 item.source = source;
Alon Albert57286f92012-10-09 14:21:38 -07001174 item.reason = reason;
1175 item.extras = extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001176 item.event = EVENT_START;
1177 mSyncHistory.add(0, item);
1178 while (mSyncHistory.size() > MAX_HISTORY) {
1179 mSyncHistory.remove(mSyncHistory.size()-1);
1180 }
1181 id = item.historyId;
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001182 if (DEBUG) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001183 }
Costin Manolache360e4542009-09-04 13:36:04 -07001184
Fred Quintanaac9385e2009-06-22 18:00:59 -07001185 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001186 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 }
1188
Fred Quintana77c560f2010-03-29 22:20:26 -07001189 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001191 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001192 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001193 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1194 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001195 SyncHistoryItem item = null;
1196 int i = mSyncHistory.size();
1197 while (i > 0) {
1198 i--;
1199 item = mSyncHistory.get(i);
1200 if (item.historyId == historyId) {
1201 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001203 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 }
Costin Manolache360e4542009-09-04 13:36:04 -07001205
Dianne Hackborn231cc602009-04-27 17:10:36 -07001206 if (item == null) {
1207 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1208 return;
1209 }
Costin Manolache360e4542009-09-04 13:36:04 -07001210
Dianne Hackborn231cc602009-04-27 17:10:36 -07001211 item.elapsedTime = elapsedTime;
1212 item.event = EVENT_STOP;
1213 item.mesg = resultMessage;
1214 item.downstreamActivity = downstreamActivity;
1215 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001216
Dianne Hackborn231cc602009-04-27 17:10:36 -07001217 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001218
Dianne Hackborn231cc602009-04-27 17:10:36 -07001219 status.numSyncs++;
1220 status.totalElapsedTime += elapsedTime;
1221 switch (item.source) {
1222 case SOURCE_LOCAL:
1223 status.numSourceLocal++;
1224 break;
1225 case SOURCE_POLL:
1226 status.numSourcePoll++;
1227 break;
1228 case SOURCE_USER:
1229 status.numSourceUser++;
1230 break;
1231 case SOURCE_SERVER:
1232 status.numSourceServer++;
1233 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001234 case SOURCE_PERIODIC:
1235 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001236 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001237 }
Costin Manolache360e4542009-09-04 13:36:04 -07001238
Dianne Hackborn231cc602009-04-27 17:10:36 -07001239 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001240 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001241 if (mDayStats[0] == null) {
1242 mDayStats[0] = new DayStats(day);
1243 } else if (day != mDayStats[0].day) {
1244 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1245 mDayStats[0] = new DayStats(day);
1246 writeStatisticsNow = true;
1247 } else if (mDayStats[0] == null) {
1248 }
1249 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001250
Dianne Hackborn231cc602009-04-27 17:10:36 -07001251 final long lastSyncTime = (item.eventTime + elapsedTime);
1252 boolean writeStatusNow = false;
1253 if (MESG_SUCCESS.equals(resultMessage)) {
1254 // - if successful, update the successful columns
1255 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1256 writeStatusNow = true;
1257 }
1258 status.lastSuccessTime = lastSyncTime;
1259 status.lastSuccessSource = item.source;
1260 status.lastFailureTime = 0;
1261 status.lastFailureSource = -1;
1262 status.lastFailureMesg = null;
1263 status.initialFailureTime = 0;
1264 ds.successCount++;
1265 ds.successTime += elapsedTime;
1266 } else if (!MESG_CANCELED.equals(resultMessage)) {
1267 if (status.lastFailureTime == 0) {
1268 writeStatusNow = true;
1269 }
1270 status.lastFailureTime = lastSyncTime;
1271 status.lastFailureSource = item.source;
1272 status.lastFailureMesg = resultMessage;
1273 if (status.initialFailureTime == 0) {
1274 status.initialFailureTime = lastSyncTime;
1275 }
1276 ds.failureCount++;
1277 ds.failureTime += elapsedTime;
1278 }
Costin Manolache360e4542009-09-04 13:36:04 -07001279
Dianne Hackborn231cc602009-04-27 17:10:36 -07001280 if (writeStatusNow) {
1281 writeStatusLocked();
1282 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1283 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1284 WRITE_STATUS_DELAY);
1285 }
1286 if (writeStatisticsNow) {
1287 writeStatisticsLocked();
1288 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1289 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1290 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001291 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001292 }
Costin Manolache360e4542009-09-04 13:36:04 -07001293
Fred Quintanaac9385e2009-06-22 18:00:59 -07001294 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001295 }
1296
1297 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001298 * Return a list of the currently active syncs. Note that the returned
1299 * items are the real, live active sync objects, so be careful what you do
1300 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001301 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001302 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001303 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001304 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001305 }
1306 }
Costin Manolache360e4542009-09-04 13:36:04 -07001307
Dianne Hackborn231cc602009-04-27 17:10:36 -07001308 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001309 * @return a copy of the current syncs data structure. Will not return
1310 * null.
1311 */
1312 public List<SyncInfo> getCurrentSyncsCopy(int userId) {
1313 synchronized (mAuthorities) {
1314 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1315 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1316 for (SyncInfo sync : syncs) {
1317 syncsCopy.add(new SyncInfo(sync));
1318 }
1319 return syncsCopy;
1320 }
1321 }
1322
1323 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1324 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1325 if (syncs == null) {
1326 syncs = new ArrayList<SyncInfo>();
1327 mCurrentSyncs.put(userId, syncs);
1328 }
1329 return syncs;
1330 }
1331
1332 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001333 * Return an array of the current sync status for all authorities. 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 ArrayList<SyncStatusInfo> getSyncStatus() {
1338 synchronized (mAuthorities) {
1339 final int N = mSyncStatus.size();
1340 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1341 for (int i=0; i<N; i++) {
1342 ops.add(mSyncStatus.valueAt(i));
1343 }
1344 return ops;
1345 }
1346 }
Costin Manolache360e4542009-09-04 13:36:04 -07001347
Dianne Hackborn231cc602009-04-27 17:10:36 -07001348 /**
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001349 * Return a copy of the specified authority with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001350 */
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001351 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(
1352 Account account, int userId, String authority) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001353 synchronized (mAuthorities) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001354 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(account, userId, authority,
1355 -1 /* assign a new identifier if creating a new authority */,
1356 true /* write to storage if this results in a change */);
1357 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1358 }
1359 }
1360
1361 /**
1362 * Return a copy of all authorities with their corresponding sync status
1363 */
1364 public ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> getCopyOfAllAuthoritiesWithSyncStatus() {
1365 synchronized (mAuthorities) {
1366 ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> infos =
1367 new ArrayList<Pair<AuthorityInfo, SyncStatusInfo>>(mAuthorities.size());
1368 for (int i = 0; i < mAuthorities.size(); i++) {
1369 infos.add(createCopyPairOfAuthorityWithSyncStatusLocked(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001370 }
1371 return infos;
1372 }
1373 }
1374
1375 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001376 * Returns the status that matches the authority and account.
1377 *
1378 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001379 * @param authority the authority whose row should be selected
Matthew Williams632515b2013-10-10 15:51:00 -07001380 * @return the SyncStatusInfo for the authority or null if none found.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001381 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001382 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, int userId,
1383 String authority) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001384 if (account == null || authority == null) {
Matthew Williams632515b2013-10-10 15:51:00 -07001385 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001386 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001387 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001388 final int N = mSyncStatus.size();
1389 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001390 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001391 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001392
Amith Yamasani04e0d262012-02-14 11:50:53 -08001393 if (ainfo != null && ainfo.authority.equals(authority)
1394 && ainfo.userId == userId
1395 && account.equals(ainfo.account)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001396 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001397 }
1398 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001399 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001400 }
1401 }
Costin Manolache360e4542009-09-04 13:36:04 -07001402
Dianne Hackborn231cc602009-04-27 17:10:36 -07001403 /**
1404 * Return true if the pending status is true of any matching authorities.
1405 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001406 public boolean isSyncPending(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001407 synchronized (mAuthorities) {
1408 final int N = mSyncStatus.size();
1409 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001410 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001411 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1412 if (ainfo == null) {
1413 continue;
1414 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001415 if (userId != ainfo.userId) {
1416 continue;
1417 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001418 if (account != null && !ainfo.account.equals(account)) {
1419 continue;
1420 }
1421 if (ainfo.authority.equals(authority) && cur.pending) {
1422 return true;
1423 }
1424 }
1425 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
1427 }
1428
1429 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001430 * Return an array of the current sync status for all authorities. Note
1431 * that the objects inside the array are the real, live status objects,
1432 * so be careful what you do with them.
1433 */
1434 public ArrayList<SyncHistoryItem> getSyncHistory() {
1435 synchronized (mAuthorities) {
1436 final int N = mSyncHistory.size();
1437 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1438 for (int i=0; i<N; i++) {
1439 items.add(mSyncHistory.get(i));
1440 }
1441 return items;
1442 }
1443 }
Costin Manolache360e4542009-09-04 13:36:04 -07001444
Dianne Hackborn231cc602009-04-27 17:10:36 -07001445 /**
1446 * Return an array of the current per-day statistics. Note
1447 * that the objects inside the array are the real, live status objects,
1448 * so be careful what you do with them.
1449 */
1450 public DayStats[] getDayStatistics() {
1451 synchronized (mAuthorities) {
1452 DayStats[] ds = new DayStats[mDayStats.length];
1453 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1454 return ds;
1455 }
1456 }
Costin Manolache360e4542009-09-04 13:36:04 -07001457
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001458 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1459 AuthorityInfo authorityInfo) {
1460 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1461 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1462 }
1463
Dianne Hackborn55280a92009-05-07 15:53:46 -07001464 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001465 mCal.setTimeInMillis(System.currentTimeMillis());
1466 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1467 if (mYear != mCal.get(Calendar.YEAR)) {
1468 mYear = mCal.get(Calendar.YEAR);
1469 mCal.clear();
1470 mCal.set(Calendar.YEAR, mYear);
1471 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1472 }
1473 return dayOfYear + mYearInDays;
1474 }
Costin Manolache360e4542009-09-04 13:36:04 -07001475
Dianne Hackborn231cc602009-04-27 17:10:36 -07001476 /**
1477 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001478 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001479 * @param accountName The name of the account for the authority.
1480 * @param authorityName The name of the authority itself.
1481 * @param tag If non-null, this will be used in a log message if the
1482 * requested authority does not exist.
1483 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001484 private AuthorityInfo getAuthorityLocked(Account accountName, int userId, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001485 String tag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001486 AccountAndUser au = new AccountAndUser(accountName, userId);
1487 AccountInfo accountInfo = mAccounts.get(au);
1488 if (accountInfo == null) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001489 if (tag != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001490 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001491 Log.v(TAG, tag + ": unknown account " + au);
Fred Quintanab763ab22009-08-18 18:07:30 -07001492 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001493 }
1494 return null;
1495 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001496 AuthorityInfo authority = accountInfo.authorities.get(authorityName);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001497 if (authority == null) {
1498 if (tag != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001499 if (DEBUG) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001500 Log.v(TAG, tag + ": unknown authority " + authorityName);
1501 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001502 }
1503 return null;
1504 }
Costin Manolache360e4542009-09-04 13:36:04 -07001505
Dianne Hackborn231cc602009-04-27 17:10:36 -07001506 return authority;
1507 }
Costin Manolache360e4542009-09-04 13:36:04 -07001508
Matthew Williamsfa774182013-06-18 15:44:11 -07001509 /**
1510 * Retrieve an authority, returning null if one does not exist.
1511 *
1512 * @param service The service name used for this sync.
1513 * @param userId The user for whom this sync is scheduled.
1514 * @param tag If non-null, this will be used in a log message if the
1515 * requested authority does not exist.
1516 */
1517 private AuthorityInfo getAuthorityLocked(ComponentName service, int userId, String tag) {
1518 AuthorityInfo authority = mServices.get(service).get(userId);
1519 if (authority == null) {
1520 if (tag != null) {
1521 if (DEBUG) {
1522 Log.v(TAG, tag + " No authority info found for " + service + " for user "
1523 + userId);
1524 }
1525 }
1526 return null;
1527 }
1528 return authority;
1529 }
1530
1531 /**
1532 * @param cname identifier for the service.
1533 * @param userId for the syncs corresponding to this authority.
1534 * @param ident unique identifier for authority. -1 for none.
1535 * @param doWrite if true, update the accounts.xml file on the disk.
1536 * @return the authority that corresponds to the provided sync service, creating it if none
1537 * exists.
1538 */
1539 private AuthorityInfo getOrCreateAuthorityLocked(ComponentName cname, int userId, int ident,
1540 boolean doWrite) {
1541 SparseArray<AuthorityInfo> aInfo = mServices.get(cname);
1542 if (aInfo == null) {
1543 aInfo = new SparseArray<AuthorityInfo>();
1544 mServices.put(cname, aInfo);
1545 }
1546 AuthorityInfo authority = aInfo.get(userId);
1547 if (authority == null) {
1548 if (ident < 0) {
1549 ident = mNextAuthorityId;
1550 mNextAuthorityId++;
1551 doWrite = true;
1552 }
1553 if (DEBUG) {
1554 Log.v(TAG, "created a new AuthorityInfo for " + cname.getPackageName()
1555 + ", " + cname.getClassName()
1556 + ", user: " + userId);
1557 }
1558 authority = new AuthorityInfo(cname, userId, ident);
1559 aInfo.put(userId, authority);
1560 mAuthorities.put(ident, authority);
1561 if (doWrite) {
1562 writeAccountInfoLocked();
1563 }
1564 }
1565 return authority;
1566 }
1567
Amith Yamasani04e0d262012-02-14 11:50:53 -08001568 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName, int userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001569 String authorityName, int ident, boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001570 AccountAndUser au = new AccountAndUser(accountName, userId);
1571 AccountInfo account = mAccounts.get(au);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001572 if (account == null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001573 account = new AccountInfo(au);
1574 mAccounts.put(au, account);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001575 }
1576 AuthorityInfo authority = account.authorities.get(authorityName);
1577 if (authority == null) {
1578 if (ident < 0) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001579 ident = mNextAuthorityId;
1580 mNextAuthorityId++;
1581 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001582 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001583 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001584 Log.v(TAG, "created a new AuthorityInfo for " + accountName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001585 + ", user " + userId
1586 + ", provider " + authorityName);
Fred Quintana77c560f2010-03-29 22:20:26 -07001587 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001588 authority = new AuthorityInfo(accountName, userId, authorityName, ident);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001589 account.authorities.put(authorityName, authority);
1590 mAuthorities.put(ident, authority);
1591 if (doWrite) {
1592 writeAccountInfoLocked();
1593 }
1594 }
Costin Manolache360e4542009-09-04 13:36:04 -07001595
Dianne Hackborn231cc602009-04-27 17:10:36 -07001596 return authority;
1597 }
Costin Manolache360e4542009-09-04 13:36:04 -07001598
Amith Yamasani04e0d262012-02-14 11:50:53 -08001599 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1600 boolean doWrite) {
1601 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001602 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001603 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1604 if (authorityInfo != null) {
1605 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001606 if (doWrite) {
1607 writeAccountInfoLocked();
1608 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001609 }
1610 }
1611 }
1612
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001613 /**
1614 * Updates (in a synchronized way) the periodic sync time of the specified
1615 * authority id and target periodic sync
1616 */
1617 public void setPeriodicSyncTime(
Matthew Williamsfa774182013-06-18 15:44:11 -07001618 int authorityId, PeriodicSync targetPeriodicSync, long when) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001619 boolean found = false;
1620 final AuthorityInfo authorityInfo;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001621 synchronized (mAuthorities) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001622 authorityInfo = mAuthorities.get(authorityId);
1623 for (int i = 0; i < authorityInfo.periodicSyncs.size(); i++) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001624 PeriodicSync periodicSync = authorityInfo.periodicSyncs.get(i);
1625 if (targetPeriodicSync.equals(periodicSync)) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001626 mSyncStatus.get(authorityId).setPeriodicSyncTime(i, when);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001627 found = true;
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001628 break;
1629 }
1630 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001631 }
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001632 if (!found) {
1633 Log.w(TAG, "Ignoring setPeriodicSyncTime request for a sync that does not exist. " +
1634 "Authority: " + authorityInfo.authority);
1635 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001636 }
1637
Dianne Hackborn231cc602009-04-27 17:10:36 -07001638 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1639 SyncStatusInfo status = mSyncStatus.get(authorityId);
1640 if (status == null) {
1641 status = new SyncStatusInfo(authorityId);
1642 mSyncStatus.put(authorityId, status);
1643 }
1644 return status;
1645 }
Costin Manolache360e4542009-09-04 13:36:04 -07001646
Dianne Hackborn55280a92009-05-07 15:53:46 -07001647 public void writeAllState() {
1648 synchronized (mAuthorities) {
1649 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001650
Dianne Hackborn55280a92009-05-07 15:53:46 -07001651 if (mNumPendingFinished > 0) {
1652 // Only write these if they are out of date.
1653 writePendingOperationsLocked();
1654 }
Costin Manolache360e4542009-09-04 13:36:04 -07001655
Dianne Hackborn55280a92009-05-07 15:53:46 -07001656 // Just always write these... they are likely out of date.
1657 writeStatusLocked();
1658 writeStatisticsLocked();
1659 }
1660 }
Costin Manolache360e4542009-09-04 13:36:04 -07001661
Dianne Hackborn231cc602009-04-27 17:10:36 -07001662 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001663 * public for testing
1664 */
1665 public void clearAndReadState() {
1666 synchronized (mAuthorities) {
1667 mAuthorities.clear();
1668 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001669 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001670 mPendingOperations.clear();
1671 mSyncStatus.clear();
1672 mSyncHistory.clear();
1673
1674 readAccountInfoLocked();
1675 readStatusLocked();
1676 readPendingOperationsLocked();
1677 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001678 readAndDeleteLegacyAccountInfoLocked();
1679 writeAccountInfoLocked();
1680 writeStatusLocked();
1681 writePendingOperationsLocked();
1682 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001683 }
1684 }
1685
1686 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001687 * Read all account information back in to the initial engine state.
1688 */
1689 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001690 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001691 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001693 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001694 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
1695 Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1696 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001697 XmlPullParser parser = Xml.newPullParser();
1698 parser.setInput(fis, null);
1699 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001700 while (eventType != XmlPullParser.START_TAG &&
1701 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001702 eventType = parser.next();
1703 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001704 if (eventType == XmlPullParser.END_DOCUMENT) {
1705 Log.i(TAG, "No initial accounts");
1706 return;
1707 }
1708
Dianne Hackborn231cc602009-04-27 17:10:36 -07001709 String tagName = parser.getName();
1710 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001711 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001712 String versionString = parser.getAttributeValue(null, "version");
1713 int version;
1714 try {
1715 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1716 } catch (NumberFormatException e) {
1717 version = 0;
1718 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001719 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001720 try {
1721 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1722 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1723 } catch (NumberFormatException e) {
1724 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001725 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001726 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1727 try {
1728 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1729 } catch (NumberFormatException e) {
1730 mSyncRandomOffset = 0;
1731 }
1732 if (mSyncRandomOffset == 0) {
1733 Random random = new Random(System.currentTimeMillis());
1734 mSyncRandomOffset = random.nextInt(86400);
1735 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001736 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001737 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001738 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001739 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001740 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001741 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001742 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001743 if (parser.getDepth() == 2) {
1744 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001745 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001746 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001747 if (authority.ident > highestAuthorityId) {
1748 highestAuthorityId = authority.ident;
1749 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001750 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1751 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001752 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001753 } else if (parser.getDepth() == 3) {
1754 if ("periodicSync".equals(tagName) && authority != null) {
1755 periodicSync = parsePeriodicSync(parser, authority);
1756 }
1757 } else if (parser.getDepth() == 4 && periodicSync != null) {
1758 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001759 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001760 }
1761 }
1762 }
1763 eventType = parser.next();
1764 } while (eventType != XmlPullParser.END_DOCUMENT);
1765 }
1766 } catch (XmlPullParserException e) {
1767 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001768 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001769 } catch (java.io.IOException e) {
1770 if (fis == null) Log.i(TAG, "No initial accounts");
1771 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001772 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001773 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001774 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001775 if (fis != null) {
1776 try {
1777 fis.close();
1778 } catch (java.io.IOException e1) {
1779 }
1780 }
1781 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001782
Fred Quintana77c560f2010-03-29 22:20:26 -07001783 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001784 }
Costin Manolache360e4542009-09-04 13:36:04 -07001785
Fred Quintanafb084402010-03-23 17:57:03 -07001786 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001787 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1788 * pending.xml was used starting in KLP.
1789 * @param syncDir directory where the sync files are located.
1790 */
1791 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1792 File file = new File(syncDir, "pending.bin");
1793 if (!file.exists()) {
1794 return;
1795 } else {
1796 file.delete();
1797 }
1798 }
1799
1800 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001801 * some authority names have changed. copy over their settings and delete the old ones
1802 * @return true if a change was made
1803 */
1804 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1805 boolean writeNeeded = false;
1806
1807 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1808 final int N = mAuthorities.size();
1809 for (int i=0; i<N; i++) {
1810 AuthorityInfo authority = mAuthorities.valueAt(i);
1811 // skip this authority if it isn't one of the renamed ones
1812 final String newAuthorityName = sAuthorityRenames.get(authority.authority);
1813 if (newAuthorityName == null) {
1814 continue;
1815 }
1816
1817 // remember this authority so we can remove it later. we can't remove it
1818 // now without messing up this loop iteration
1819 authoritiesToRemove.add(authority);
1820
1821 // this authority isn't enabled, no need to copy it to the new authority name since
1822 // the default is "disabled"
1823 if (!authority.enabled) {
1824 continue;
1825 }
1826
1827 // if we already have a record of this new authority then don't copy over the settings
Amith Yamasani04e0d262012-02-14 11:50:53 -08001828 if (getAuthorityLocked(authority.account, authority.userId, newAuthorityName, "cleanup")
1829 != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001830 continue;
1831 }
1832
1833 AuthorityInfo newAuthority = getOrCreateAuthorityLocked(authority.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001834 authority.userId, newAuthorityName, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001835 newAuthority.enabled = true;
1836 writeNeeded = true;
1837 }
1838
1839 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001840 removeAuthorityLocked(authorityInfo.account, authorityInfo.userId,
1841 authorityInfo.authority, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001842 writeNeeded = true;
1843 }
1844
1845 return writeNeeded;
1846 }
1847
Amith Yamasani04e0d262012-02-14 11:50:53 -08001848 private void parseListenForTickles(XmlPullParser parser) {
1849 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1850 int userId = 0;
1851 try {
1852 userId = Integer.parseInt(user);
1853 } catch (NumberFormatException e) {
1854 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1855 } catch (NullPointerException e) {
1856 Log.e(TAG, "the user in listen-for-tickles is null", e);
1857 }
1858 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1859 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1860 mMasterSyncAutomatically.put(userId, listen);
1861 }
1862
Fred Quintanac2e46912010-03-15 16:10:44 -07001863 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001864 AuthorityInfo authority = null;
1865 int id = -1;
1866 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001867 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001868 } catch (NumberFormatException e) {
1869 Log.e(TAG, "error parsing the id of the authority", e);
1870 } catch (NullPointerException e) {
1871 Log.e(TAG, "the id of the authority is null", e);
1872 }
1873 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001874 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001875 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001876 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001877 String accountName = parser.getAttributeValue(null, "account");
1878 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001879 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001880 String packageName = parser.getAttributeValue(null, "package");
1881 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001882 int userId = user == null ? 0 : Integer.parseInt(user);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001883 if (accountType == null) {
1884 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001885 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001886 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001887 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001888 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
1889 Log.v(TAG, "Adding authority: account="
1890 + accountName + " auth=" + authorityName
1891 + " user=" + userId
1892 + " enabled=" + enabled
1893 + " syncable=" + syncable);
1894 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001895 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001896 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001897 Log.v(TAG, "Creating entry");
1898 }
1899 if (accountName != null && accountType != null) {
1900 authority = getOrCreateAuthorityLocked(
Matthew Williamsba352712013-08-13 15:53:31 -07001901 new Account(accountName, accountType), userId, authorityName, id,
1902 false);
Matthew Williamsfa774182013-06-18 15:44:11 -07001903 } else {
1904 authority = getOrCreateAuthorityLocked(
1905 new ComponentName(packageName, className), userId, id, false);
1906 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001907 // If the version is 0 then we are upgrading from a file format that did not
1908 // know about periodic syncs. In that case don't clear the list since we
Matthew Williamsfa774182013-06-18 15:44:11 -07001909 // want the default, which is a daily periodic sync.
Fred Quintanac2e46912010-03-15 16:10:44 -07001910 // Otherwise clear out this default list since we will populate it later with
1911 // the periodic sync descriptions that are read from the configuration file.
1912 if (version > 0) {
1913 authority.periodicSyncs.clear();
1914 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001915 }
1916 if (authority != null) {
1917 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1918 if ("unknown".equals(syncable)) {
1919 authority.syncable = -1;
1920 } else {
1921 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07001922 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001923 }
1924 } else {
1925 Log.w(TAG, "Failure adding authority: account="
1926 + accountName + " auth=" + authorityName
1927 + " enabled=" + enabled
1928 + " syncable=" + syncable);
1929 }
1930 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001931 return authority;
1932 }
1933
Matthew Williamsfa774182013-06-18 15:44:11 -07001934 /**
1935 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1936 */
1937 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1938 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001939 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001940 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001941 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001942 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001943 try {
1944 period = Long.parseLong(periodValue);
1945 } catch (NumberFormatException e) {
1946 Log.e(TAG, "error parsing the period of a periodic sync", e);
1947 return null;
1948 } catch (NullPointerException e) {
1949 Log.e(TAG, "the period of a periodic sync is null", e);
1950 return null;
1951 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001952 try {
1953 flextime = Long.parseLong(flexValue);
1954 } catch (NumberFormatException e) {
1955 Log.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue);
1956 flextime = calculateDefaultFlexTime(period);
1957 } catch (NullPointerException expected) {
1958 flextime = calculateDefaultFlexTime(period);
1959 Log.d(TAG, "No flex time specified for this sync, using a default. period: "
1960 + period + " flex: " + flextime);
1961 }
1962 final PeriodicSync periodicSync =
1963 new PeriodicSync(authority.account, authority.authority, extras,
1964 period, flextime);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001965 authority.periodicSyncs.add(periodicSync);
1966 return periodicSync;
1967 }
1968
Matthew Williamsfa774182013-06-18 15:44:11 -07001969 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001970 String name = parser.getAttributeValue(null, "name");
1971 String type = parser.getAttributeValue(null, "type");
1972 String value1 = parser.getAttributeValue(null, "value1");
1973 String value2 = parser.getAttributeValue(null, "value2");
1974
1975 try {
1976 if ("long".equals(type)) {
1977 extras.putLong(name, Long.parseLong(value1));
1978 } else if ("integer".equals(type)) {
1979 extras.putInt(name, Integer.parseInt(value1));
1980 } else if ("double".equals(type)) {
1981 extras.putDouble(name, Double.parseDouble(value1));
1982 } else if ("float".equals(type)) {
1983 extras.putFloat(name, Float.parseFloat(value1));
1984 } else if ("boolean".equals(type)) {
1985 extras.putBoolean(name, Boolean.parseBoolean(value1));
1986 } else if ("string".equals(type)) {
1987 extras.putString(name, value1);
1988 } else if ("account".equals(type)) {
1989 extras.putParcelable(name, new Account(value1, value2));
1990 }
1991 } catch (NumberFormatException e) {
1992 Log.e(TAG, "error parsing bundle value", e);
1993 } catch (NullPointerException e) {
1994 Log.e(TAG, "error parsing bundle value", e);
1995 }
1996 }
1997
Dianne Hackborn231cc602009-04-27 17:10:36 -07001998 /**
1999 * Write all account information to the account file.
2000 */
2001 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002002 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2003 Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
2004 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002005 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07002006
Dianne Hackborn231cc602009-04-27 17:10:36 -07002007 try {
2008 fos = mAccountInfoFile.startWrite();
2009 XmlSerializer out = new FastXmlSerializer();
2010 out.setOutput(fos, "utf-8");
2011 out.startDocument(null, true);
2012 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07002013
Dianne Hackborn231cc602009-04-27 17:10:36 -07002014 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07002015 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002016 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07002017 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002018
2019 // Write the Sync Automatically flags for each user
2020 final int M = mMasterSyncAutomatically.size();
2021 for (int m = 0; m < M; m++) {
2022 int userId = mMasterSyncAutomatically.keyAt(m);
2023 Boolean listen = mMasterSyncAutomatically.valueAt(m);
2024 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
2025 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
2026 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
2027 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002028 }
Costin Manolache360e4542009-09-04 13:36:04 -07002029
Dianne Hackborn231cc602009-04-27 17:10:36 -07002030 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07002031 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07002032 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002033 out.startTag(null, "authority");
2034 out.attribute(null, "id", Integer.toString(authority.ident));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002035 out.attribute(null, XML_ATTR_USER, Integer.toString(authority.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002036 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Matthew Williamsfa774182013-06-18 15:44:11 -07002037 if (authority.service == null) {
2038 out.attribute(null, "account", authority.account.name);
2039 out.attribute(null, "type", authority.account.type);
2040 out.attribute(null, "authority", authority.authority);
2041 } else {
2042 out.attribute(null, "package", authority.service.getPackageName());
2043 out.attribute(null, "class", authority.service.getClassName());
2044 }
Fred Quintana5e787c42009-08-16 23:13:53 -07002045 if (authority.syncable < 0) {
2046 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07002047 } else {
2048 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07002049 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002050 for (PeriodicSync periodicSync : authority.periodicSyncs) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002051 out.startTag(null, "periodicSync");
Matthew Williamsfa774182013-06-18 15:44:11 -07002052 out.attribute(null, "period", Long.toString(periodicSync.period));
2053 out.attribute(null, "flex", Long.toString(periodicSync.flexTime));
2054 final Bundle extras = periodicSync.extras;
2055 extrasToXml(out, extras);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002056 out.endTag(null, "periodicSync");
2057 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002058 out.endTag(null, "authority");
2059 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002060 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002061 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002062 mAccountInfoFile.finishWrite(fos);
2063 } catch (java.io.IOException e1) {
2064 Log.w(TAG, "Error writing accounts", e1);
2065 if (fos != null) {
2066 mAccountInfoFile.failWrite(fos);
2067 }
2068 }
2069 }
Costin Manolache360e4542009-09-04 13:36:04 -07002070
Dianne Hackborn231cc602009-04-27 17:10:36 -07002071 static int getIntColumn(Cursor c, String name) {
2072 return c.getInt(c.getColumnIndex(name));
2073 }
Costin Manolache360e4542009-09-04 13:36:04 -07002074
Dianne Hackborn231cc602009-04-27 17:10:36 -07002075 static long getLongColumn(Cursor c, String name) {
2076 return c.getLong(c.getColumnIndex(name));
2077 }
Costin Manolache360e4542009-09-04 13:36:04 -07002078
Dianne Hackborn231cc602009-04-27 17:10:36 -07002079 /**
2080 * Load sync engine state from the old syncmanager database, and then
2081 * erase it. Note that we don't deal with pending operations, active
2082 * sync, or history.
2083 */
Fred Quintana77c560f2010-03-29 22:20:26 -07002084 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002085 // Look for old database to initialize from.
2086 File file = mContext.getDatabasePath("syncmanager.db");
2087 if (!file.exists()) {
2088 return;
2089 }
2090 String path = file.getPath();
2091 SQLiteDatabase db = null;
2092 try {
2093 db = SQLiteDatabase.openDatabase(path, null,
2094 SQLiteDatabase.OPEN_READONLY);
2095 } catch (SQLiteException e) {
2096 }
Costin Manolache360e4542009-09-04 13:36:04 -07002097
Dianne Hackborn231cc602009-04-27 17:10:36 -07002098 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002099 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07002100
Dianne Hackborn231cc602009-04-27 17:10:36 -07002101 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07002102 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2103 Log.v(TAG, "Reading legacy sync accounts db");
2104 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002105 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
2106 qb.setTables("stats, status");
2107 HashMap<String,String> map = new HashMap<String,String>();
2108 map.put("_id", "status._id as _id");
2109 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002110 if (hasType) {
2111 map.put("account_type", "stats.account_type as account_type");
2112 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002113 map.put("authority", "stats.authority as authority");
2114 map.put("totalElapsedTime", "totalElapsedTime");
2115 map.put("numSyncs", "numSyncs");
2116 map.put("numSourceLocal", "numSourceLocal");
2117 map.put("numSourcePoll", "numSourcePoll");
2118 map.put("numSourceServer", "numSourceServer");
2119 map.put("numSourceUser", "numSourceUser");
2120 map.put("lastSuccessSource", "lastSuccessSource");
2121 map.put("lastSuccessTime", "lastSuccessTime");
2122 map.put("lastFailureSource", "lastFailureSource");
2123 map.put("lastFailureTime", "lastFailureTime");
2124 map.put("lastFailureMesg", "lastFailureMesg");
2125 map.put("pending", "pending");
2126 qb.setProjectionMap(map);
2127 qb.appendWhere("stats._id = status.stats_id");
2128 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002130 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002131 String accountType = hasType
2132 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07002133 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07002134 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002136 String authorityName = c.getString(c.getColumnIndex("authority"));
2137 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08002138 new Account(accountName, accountType), 0 /* legacy is single-user */,
Dianne Hackborn7a135592009-05-06 00:28:37 -07002139 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002140 if (authority != null) {
2141 int i = mSyncStatus.size();
2142 boolean found = false;
2143 SyncStatusInfo st = null;
2144 while (i > 0) {
2145 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002146 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002147 if (st.authorityId == authority.ident) {
2148 found = true;
2149 break;
2150 }
2151 }
2152 if (!found) {
2153 st = new SyncStatusInfo(authority.ident);
2154 mSyncStatus.put(authority.ident, st);
2155 }
2156 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2157 st.numSyncs = getIntColumn(c, "numSyncs");
2158 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
2159 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
2160 st.numSourceServer = getIntColumn(c, "numSourceServer");
2161 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002162 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002163 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2164 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2165 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2166 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2167 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2168 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 }
Costin Manolache360e4542009-09-04 13:36:04 -07002171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002173
Dianne Hackborn231cc602009-04-27 17:10:36 -07002174 // Retrieve the settings.
2175 qb = new SQLiteQueryBuilder();
2176 qb.setTables("settings");
2177 c = qb.query(db, null, null, null, null, null, null);
2178 while (c.moveToNext()) {
2179 String name = c.getString(c.getColumnIndex("name"));
2180 String value = c.getString(c.getColumnIndex("value"));
2181 if (name == null) continue;
2182 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002183 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002184 } else if (name.startsWith("sync_provider_")) {
2185 String provider = name.substring("sync_provider_".length(),
2186 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002187 int i = mAuthorities.size();
2188 while (i > 0) {
2189 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002190 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07002191 if (authority.authority.equals(provider)) {
2192 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002193 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002194 }
2195 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 }
Costin Manolache360e4542009-09-04 13:36:04 -07002198
Dianne Hackborn231cc602009-04-27 17:10:36 -07002199 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002200
Dianne Hackborn231cc602009-04-27 17:10:36 -07002201 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002202
Dianne Hackborn231cc602009-04-27 17:10:36 -07002203 (new File(path)).delete();
2204 }
2205 }
Costin Manolache360e4542009-09-04 13:36:04 -07002206
Dianne Hackborn231cc602009-04-27 17:10:36 -07002207 public static final int STATUS_FILE_END = 0;
2208 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002209
Dianne Hackborn231cc602009-04-27 17:10:36 -07002210 /**
2211 * Read all sync status back in to the initial engine state.
2212 */
2213 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002214 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2215 Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
2216 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002217 try {
2218 byte[] data = mStatusFile.readFully();
2219 Parcel in = Parcel.obtain();
2220 in.unmarshall(data, 0, data.length);
2221 in.setDataPosition(0);
2222 int token;
2223 while ((token=in.readInt()) != STATUS_FILE_END) {
2224 if (token == STATUS_FILE_ITEM) {
2225 SyncStatusInfo status = new SyncStatusInfo(in);
2226 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2227 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002228 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2229 Log.v(TAG, "Adding status for id "
2230 + status.authorityId);
2231 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002232 mSyncStatus.put(status.authorityId, status);
2233 }
2234 } else {
2235 // Ooops.
2236 Log.w(TAG, "Unknown status token: " + token);
2237 break;
2238 }
2239 }
2240 } catch (java.io.IOException e) {
2241 Log.i(TAG, "No initial status");
2242 }
2243 }
Costin Manolache360e4542009-09-04 13:36:04 -07002244
Dianne Hackborn231cc602009-04-27 17:10:36 -07002245 /**
2246 * Write all sync status to the sync status file.
2247 */
2248 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002249 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2250 Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
2251 }
Costin Manolache360e4542009-09-04 13:36:04 -07002252
Dianne Hackborn231cc602009-04-27 17:10:36 -07002253 // The file is being written, so we don't need to have a scheduled
2254 // write until the next change.
2255 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002256
Dianne Hackborn231cc602009-04-27 17:10:36 -07002257 FileOutputStream fos = null;
2258 try {
2259 fos = mStatusFile.startWrite();
2260 Parcel out = Parcel.obtain();
2261 final int N = mSyncStatus.size();
2262 for (int i=0; i<N; i++) {
2263 SyncStatusInfo status = mSyncStatus.valueAt(i);
2264 out.writeInt(STATUS_FILE_ITEM);
2265 status.writeToParcel(out, 0);
2266 }
2267 out.writeInt(STATUS_FILE_END);
2268 fos.write(out.marshall());
2269 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002270
Dianne Hackborn231cc602009-04-27 17:10:36 -07002271 mStatusFile.finishWrite(fos);
2272 } catch (java.io.IOException e1) {
2273 Log.w(TAG, "Error writing status", e1);
2274 if (fos != null) {
2275 mStatusFile.failWrite(fos);
2276 }
2277 }
2278 }
Costin Manolache360e4542009-09-04 13:36:04 -07002279
Matthew Williamsba352712013-08-13 15:53:31 -07002280 public static final int PENDING_OPERATION_VERSION = 3;
Costin Manolache360e4542009-09-04 13:36:04 -07002281
Matthew Williamsba352712013-08-13 15:53:31 -07002282 /** Read all pending operations back in to the initial engine state. */
Dianne Hackborn231cc602009-04-27 17:10:36 -07002283 private void readPendingOperationsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002284 FileInputStream fis = null;
2285 if (!mPendingFile.getBaseFile().exists()) {
2286 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2287 Log.v(TAG_FILE, "No pending operation file.");
2288 return;
Matthew Williamsfa774182013-06-18 15:44:11 -07002289 }
2290 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002291 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002292 fis = mPendingFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07002293 XmlPullParser parser;
2294 parser = Xml.newPullParser();
Matthew Williamsfa774182013-06-18 15:44:11 -07002295 parser.setInput(fis, null);
Matthew Williamsba352712013-08-13 15:53:31 -07002296
Matthew Williamsfa774182013-06-18 15:44:11 -07002297 int eventType = parser.getEventType();
2298 while (eventType != XmlPullParser.START_TAG &&
2299 eventType != XmlPullParser.END_DOCUMENT) {
2300 eventType = parser.next();
Matthew Williamsfa774182013-06-18 15:44:11 -07002301 }
Matthew Williamsba352712013-08-13 15:53:31 -07002302 if (eventType == XmlPullParser.END_DOCUMENT) return; // Nothing to read.
Matthew Williamsfa774182013-06-18 15:44:11 -07002303
2304 String tagName = parser.getName();
Matthew Williamsba352712013-08-13 15:53:31 -07002305 do {
Matthew Williamsfa774182013-06-18 15:44:11 -07002306 PendingOperation pop = null;
Matthew Williamsba352712013-08-13 15:53:31 -07002307 if (eventType == XmlPullParser.START_TAG) {
2308 try {
2309 tagName = parser.getName();
2310 if (parser.getDepth() == 1 && "op".equals(tagName)) {
2311 // Verify version.
2312 String versionString =
2313 parser.getAttributeValue(null, XML_ATTR_VERSION);
2314 if (versionString == null ||
2315 Integer.parseInt(versionString) != PENDING_OPERATION_VERSION) {
2316 Log.w(TAG, "Unknown pending operation version " + versionString);
2317 throw new java.io.IOException("Unknown version.");
2318 }
2319 int authorityId = Integer.valueOf(parser.getAttributeValue(
2320 null, XML_ATTR_AUTHORITYID));
2321 boolean expedited = Boolean.valueOf(parser.getAttributeValue(
2322 null, XML_ATTR_EXPEDITED));
2323 int syncSource = Integer.valueOf(parser.getAttributeValue(
2324 null, XML_ATTR_SOURCE));
2325 int reason = Integer.valueOf(parser.getAttributeValue(
2326 null, XML_ATTR_REASON));
2327 AuthorityInfo authority = mAuthorities.get(authorityId);
2328 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2329 Log.v(TAG_FILE, authorityId + " " + expedited + " " + syncSource + " "
2330 + reason);
2331 }
2332 if (authority != null) {
2333 pop = new PendingOperation(
2334 authority.account, authority.userId, reason,
2335 syncSource, authority.authority, new Bundle(),
2336 expedited);
2337 pop.flatExtras = null; // No longer used.
2338 mPendingOperations.add(pop);
2339 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2340 Log.v(TAG_FILE, "Adding pending op: "
2341 + pop.authority
Matthew Williamsfa774182013-06-18 15:44:11 -07002342 + " src=" + pop.syncSource
2343 + " reason=" + pop.reason
2344 + " expedited=" + pop.expedited);
Matthew Williamsfa774182013-06-18 15:44:11 -07002345 }
Matthew Williamsba352712013-08-13 15:53:31 -07002346 } else {
2347 // Skip non-existent authority.
2348 pop = null;
2349 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2350 Log.v(TAG_FILE, "No authority found for " + authorityId
2351 + ", skipping");
2352 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002353 }
Matthew Williamsba352712013-08-13 15:53:31 -07002354 } else if (parser.getDepth() == 2 &&
2355 pop != null &&
2356 "extra".equals(tagName)) {
2357 parseExtra(parser, pop.extras);
Matthew Williamsfa774182013-06-18 15:44:11 -07002358 }
Matthew Williamsba352712013-08-13 15:53:31 -07002359 } catch (NumberFormatException e) {
2360 Log.d(TAG, "Invalid data in xml file.", e);
Matthew Williamsfa774182013-06-18 15:44:11 -07002361 }
Matthew Williamsba352712013-08-13 15:53:31 -07002362 }
2363 eventType = parser.next();
2364 } while(eventType != XmlPullParser.END_DOCUMENT);
Matthew Williamsfa774182013-06-18 15:44:11 -07002365 } catch (java.io.IOException e) {
Matthew Williamsba352712013-08-13 15:53:31 -07002366 Log.w(TAG_FILE, "Error reading pending data.", e);
2367 } catch (XmlPullParserException e) {
2368 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2369 Log.w(TAG_FILE, "Error parsing pending ops xml.", e);
2370 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002371 } finally {
Matthew Williamsfa774182013-06-18 15:44:11 -07002372 if (fis != null) {
2373 try {
2374 fis.close();
2375 } catch (java.io.IOException e1) {}
2376 }
2377 }
2378 }
Matthew Williamsba352712013-08-13 15:53:31 -07002379
2380 private static final String XML_ATTR_AUTHORITYID = "authority_id";
2381 private static final String XML_ATTR_SOURCE = "source";
2382 private static final String XML_ATTR_EXPEDITED = "expedited";
2383 private static final String XML_ATTR_REASON = "reason";
2384 private static final String XML_ATTR_VERSION = "version";
2385
Matthew Williamsfa774182013-06-18 15:44:11 -07002386 /**
Matthew Williamsba352712013-08-13 15:53:31 -07002387 * Write all currently pending ops to the pending ops file.
Matthew Williamsfa774182013-06-18 15:44:11 -07002388 */
Matthew Williamsba352712013-08-13 15:53:31 -07002389 private void writePendingOperationsLocked() {
2390 final int N = mPendingOperations.size();
2391 FileOutputStream fos = null;
2392 try {
2393 if (N == 0) {
2394 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2395 Log.v(TAG_FILE, "Truncating " + mPendingFile.getBaseFile());
Matthew Williamsfa774182013-06-18 15:44:11 -07002396 }
Matthew Williamsba352712013-08-13 15:53:31 -07002397 mPendingFile.truncate();
2398 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002399 }
Matthew Williamsba352712013-08-13 15:53:31 -07002400 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2401 Log.v(TAG_FILE, "Writing new " + mPendingFile.getBaseFile());
2402 }
2403 fos = mPendingFile.startWrite();
2404 XmlSerializer out = new FastXmlSerializer();
2405 out.setOutput(fos, "utf-8");
2406
2407 for (int i = 0; i < N; i++) {
2408 PendingOperation pop = mPendingOperations.get(i);
2409 writePendingOperationLocked(pop, out);
2410 }
2411 out.endDocument();
2412 mPendingFile.finishWrite(fos);
2413 } catch (java.io.IOException e1) {
2414 Log.w(TAG, "Error writing pending operations", e1);
2415 if (fos != null) {
2416 mPendingFile.failWrite(fos);
2417 }
2418 }
2419 }
2420
2421 /** Write all currently pending ops to the pending ops file. */
2422 private void writePendingOperationLocked(PendingOperation pop, XmlSerializer out)
2423 throws IOException {
2424 // Pending operation.
2425 out.startTag(null, "op");
2426
2427 out.attribute(null, XML_ATTR_VERSION, Integer.toString(PENDING_OPERATION_VERSION));
2428 out.attribute(null, XML_ATTR_AUTHORITYID, Integer.toString(pop.authorityId));
2429 out.attribute(null, XML_ATTR_SOURCE, Integer.toString(pop.syncSource));
2430 out.attribute(null, XML_ATTR_EXPEDITED, Boolean.toString(pop.expedited));
2431 out.attribute(null, XML_ATTR_REASON, Integer.toString(pop.reason));
2432 extrasToXml(out, pop.extras);
2433
2434 out.endTag(null, "op");
2435 }
2436
2437 /**
2438 * Append the given operation to the pending ops file; if unable to,
2439 * write all pending ops.
2440 */
2441 private void appendPendingOperationLocked(PendingOperation op) {
2442 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2443 Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2444 }
2445 FileOutputStream fos = null;
2446 try {
2447 fos = mPendingFile.openAppend();
2448 } catch (java.io.IOException e) {
2449 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2450 Log.v(TAG, "Failed append; writing full file");
2451 }
2452 writePendingOperationsLocked();
2453 return;
2454 }
2455
2456 try {
2457 XmlSerializer out = new FastXmlSerializer();
2458 out.setOutput(fos, "utf-8");
2459 writePendingOperationLocked(op, out);
2460 out.endDocument();
2461 mPendingFile.finishWrite(fos);
2462 } catch (java.io.IOException e1) {
2463 Log.w(TAG, "Error writing appending operation", e1);
2464 mPendingFile.failWrite(fos);
2465 } finally {
2466 try {
2467 fos.close();
2468 } catch (IOException e) {}
Dianne Hackborn231cc602009-04-27 17:10:36 -07002469 }
2470 }
Costin Manolache360e4542009-09-04 13:36:04 -07002471
Dianne Hackborn231cc602009-04-27 17:10:36 -07002472 static private byte[] flattenBundle(Bundle bundle) {
2473 byte[] flatData = null;
2474 Parcel parcel = Parcel.obtain();
2475 try {
2476 bundle.writeToParcel(parcel, 0);
2477 flatData = parcel.marshall();
2478 } finally {
2479 parcel.recycle();
2480 }
2481 return flatData;
2482 }
Costin Manolache360e4542009-09-04 13:36:04 -07002483
Dianne Hackborn231cc602009-04-27 17:10:36 -07002484 static private Bundle unflattenBundle(byte[] flatData) {
2485 Bundle bundle;
2486 Parcel parcel = Parcel.obtain();
2487 try {
2488 parcel.unmarshall(flatData, 0, flatData.length);
2489 parcel.setDataPosition(0);
2490 bundle = parcel.readBundle();
2491 } catch (RuntimeException e) {
2492 // A RuntimeException is thrown if we were unable to parse the parcel.
2493 // Create an empty parcel in this case.
2494 bundle = new Bundle();
2495 } finally {
2496 parcel.recycle();
2497 }
2498 return bundle;
2499 }
Costin Manolache360e4542009-09-04 13:36:04 -07002500
Matthew Williamsfa774182013-06-18 15:44:11 -07002501 private void extrasToXml(XmlSerializer out, Bundle extras) throws java.io.IOException {
2502 for (String key : extras.keySet()) {
2503 out.startTag(null, "extra");
2504 out.attribute(null, "name", key);
2505 final Object value = extras.get(key);
2506 if (value instanceof Long) {
2507 out.attribute(null, "type", "long");
2508 out.attribute(null, "value1", value.toString());
2509 } else if (value instanceof Integer) {
2510 out.attribute(null, "type", "integer");
2511 out.attribute(null, "value1", value.toString());
2512 } else if (value instanceof Boolean) {
2513 out.attribute(null, "type", "boolean");
2514 out.attribute(null, "value1", value.toString());
2515 } else if (value instanceof Float) {
2516 out.attribute(null, "type", "float");
2517 out.attribute(null, "value1", value.toString());
2518 } else if (value instanceof Double) {
2519 out.attribute(null, "type", "double");
2520 out.attribute(null, "value1", value.toString());
2521 } else if (value instanceof String) {
2522 out.attribute(null, "type", "string");
2523 out.attribute(null, "value1", value.toString());
2524 } else if (value instanceof Account) {
2525 out.attribute(null, "type", "account");
2526 out.attribute(null, "value1", ((Account)value).name);
2527 out.attribute(null, "value2", ((Account)value).type);
2528 }
2529 out.endTag(null, "extra");
2530 }
2531 }
2532
Alon Albert57286f92012-10-09 14:21:38 -07002533 private void requestSync(Account account, int userId, int reason, String authority,
2534 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002535 // If this is happening in the system process, then call the syncrequest listener
2536 // to make a request back to the SyncManager directly.
2537 // If this is probably a test instance, then call back through the ContentResolver
2538 // which will know which userId to apply based on the Binder id.
2539 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2540 && mSyncRequestListener != null) {
Alon Albert57286f92012-10-09 14:21:38 -07002541 mSyncRequestListener.onSyncRequest(account, userId, reason, authority, extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002542 } else {
2543 ContentResolver.requestSync(account, authority, extras);
2544 }
2545 }
2546
Dianne Hackborn231cc602009-04-27 17:10:36 -07002547 public static final int STATISTICS_FILE_END = 0;
2548 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2549 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002550
Dianne Hackborn231cc602009-04-27 17:10:36 -07002551 /**
2552 * Read all sync statistics back in to the initial engine state.
2553 */
2554 private void readStatisticsLocked() {
2555 try {
2556 byte[] data = mStatisticsFile.readFully();
2557 Parcel in = Parcel.obtain();
2558 in.unmarshall(data, 0, data.length);
2559 in.setDataPosition(0);
2560 int token;
2561 int index = 0;
2562 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2563 if (token == STATISTICS_FILE_ITEM
2564 || token == STATISTICS_FILE_ITEM_OLD) {
2565 int day = in.readInt();
2566 if (token == STATISTICS_FILE_ITEM_OLD) {
2567 day = day - 2009 + 14245; // Magic!
2568 }
2569 DayStats ds = new DayStats(day);
2570 ds.successCount = in.readInt();
2571 ds.successTime = in.readLong();
2572 ds.failureCount = in.readInt();
2573 ds.failureTime = in.readLong();
2574 if (index < mDayStats.length) {
2575 mDayStats[index] = ds;
2576 index++;
2577 }
2578 } else {
2579 // Ooops.
2580 Log.w(TAG, "Unknown stats token: " + token);
2581 break;
2582 }
2583 }
2584 } catch (java.io.IOException e) {
2585 Log.i(TAG, "No initial statistics");
2586 }
2587 }
Costin Manolache360e4542009-09-04 13:36:04 -07002588
Dianne Hackborn231cc602009-04-27 17:10:36 -07002589 /**
2590 * Write all sync statistics to the sync status file.
2591 */
2592 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002593 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2594 Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
2595 }
Costin Manolache360e4542009-09-04 13:36:04 -07002596
Dianne Hackborn231cc602009-04-27 17:10:36 -07002597 // The file is being written, so we don't need to have a scheduled
2598 // write until the next change.
2599 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002600
Dianne Hackborn231cc602009-04-27 17:10:36 -07002601 FileOutputStream fos = null;
2602 try {
2603 fos = mStatisticsFile.startWrite();
2604 Parcel out = Parcel.obtain();
2605 final int N = mDayStats.length;
2606 for (int i=0; i<N; i++) {
2607 DayStats ds = mDayStats[i];
2608 if (ds == null) {
2609 break;
2610 }
2611 out.writeInt(STATISTICS_FILE_ITEM);
2612 out.writeInt(ds.day);
2613 out.writeInt(ds.successCount);
2614 out.writeLong(ds.successTime);
2615 out.writeInt(ds.failureCount);
2616 out.writeLong(ds.failureTime);
2617 }
2618 out.writeInt(STATISTICS_FILE_END);
2619 fos.write(out.marshall());
2620 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002621
Dianne Hackborn231cc602009-04-27 17:10:36 -07002622 mStatisticsFile.finishWrite(fos);
2623 } catch (java.io.IOException e1) {
2624 Log.w(TAG, "Error writing stats", e1);
2625 if (fos != null) {
2626 mStatisticsFile.failWrite(fos);
2627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 }
2629 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002630
2631 /**
2632 * Dump state of PendingOperations.
2633 */
2634 public void dumpPendingOperations(StringBuilder sb) {
2635 sb.append("Pending Ops: ").append(mPendingOperations.size()).append(" operation(s)\n");
2636 for (PendingOperation pop : mPendingOperations) {
2637 sb.append("(" + pop.account)
Matthew Williamsba352712013-08-13 15:53:31 -07002638 .append(", u" + pop.userId)
Matthew Williamsfa774182013-06-18 15:44:11 -07002639 .append(", " + pop.authority)
2640 .append(", " + pop.extras)
2641 .append(")\n");
2642 }
2643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644}