blob: e3693f80b11fc7e7a62a60fae03eb79e62c1575a [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 Williamsfa774182013-06-18 15:44:11 -070074 private static final boolean DEBUG = true;
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
Alon Alberted1d2532011-02-15 14:02:14 -0800713 public void clearAllBackoffs(SyncQueue syncQueue) {
Alon Albert744e310f2010-12-14 11:37:20 -0800714 boolean changed = false;
715 synchronized (mAuthorities) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700716 synchronized (syncQueue) {
717 for (AccountInfo accountInfo : mAccounts.values()) {
718 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
719 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
720 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800721 if (DEBUG) {
Jeff Sharkeya706e2f2012-10-16 12:02:42 -0700722 Log.v(TAG, "clearAllBackoffs:"
723 + " authority:" + authorityInfo.authority
724 + " account:" + accountInfo.accountAndUser.account.name
725 + " user:" + accountInfo.accountAndUser.userId
726 + " backoffTime was: " + authorityInfo.backoffTime
727 + " backoffDelay was: " + authorityInfo.backoffDelay);
728 }
729 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
730 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
731 syncQueue.onBackoffChanged(accountInfo.accountAndUser.account,
732 accountInfo.accountAndUser.userId, authorityInfo.authority, 0);
733 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800734 }
Alon Albert744e310f2010-12-14 11:37:20 -0800735 }
736 }
737 }
738 }
739
740 if (changed) {
741 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
742 }
743 }
744
Amith Yamasani04e0d262012-02-14 11:50:53 -0800745 public void setDelayUntilTime(Account account, int userId, String providerName,
746 long delayUntil) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800747 if (DEBUG) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800748 Log.v(TAG, "setDelayUntil: " + account + ", provider " + providerName
Amith Yamasani04e0d262012-02-14 11:50:53 -0800749 + ", user " + userId + " -> delayUntil " + delayUntil);
Fred Quintana307da1a2010-01-21 14:24:20 -0800750 }
751 synchronized (mAuthorities) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800752 AuthorityInfo authority = getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -0800753 account, userId, providerName, -1 /* ident */, true);
Fred Quintana307da1a2010-01-21 14:24:20 -0800754 if (authority.delayUntil == delayUntil) {
755 return;
756 }
757 authority.delayUntil = delayUntil;
Fred Quintana307da1a2010-01-21 14:24:20 -0800758 }
759
760 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
761 }
762
Amith Yamasani04e0d262012-02-14 11:50:53 -0800763 public long getDelayUntilTime(Account account, int userId, String providerName) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800764 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800765 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
766 "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800767 if (authority == null) {
768 return 0;
769 }
770 return authority.delayUntil;
771 }
772 }
773
Matthew Williamsfa774182013-06-18 15:44:11 -0700774 private void updateOrRemovePeriodicSync(PeriodicSync toUpdate, int userId, boolean add) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800775 if (DEBUG) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700776 Log.v(TAG, "addOrRemovePeriodicSync: " + toUpdate.account + ", user " + userId
777 + ", provider " + toUpdate.authority
778 + " -> period " + toUpdate.period + ", extras " + toUpdate.extras);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800779 }
780 synchronized (mAuthorities) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700781 if (toUpdate.period <= 0 && add) {
Matthew Williamsba352712013-08-13 15:53:31 -0700782 Log.e(TAG, "period < 0, should never happen in updateOrRemovePeriodicSync: add-"
783 + add);
Matthew Williamsfa774182013-06-18 15:44:11 -0700784 }
785 if (toUpdate.extras == null) {
Matthew Williamsba352712013-08-13 15:53:31 -0700786 Log.e(TAG, "null extras, should never happen in updateOrRemovePeriodicSync: add-"
787 + add);
Matthew Williamsfa774182013-06-18 15:44:11 -0700788 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700789 try {
790 AuthorityInfo authority =
Matthew Williamsfa774182013-06-18 15:44:11 -0700791 getOrCreateAuthorityLocked(toUpdate.account, userId, toUpdate.authority,
792 -1, false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700793 if (add) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700794 // add this periodic sync if an equivalent periodic doesn't already exist.
Fred Quintana77c560f2010-03-29 22:20:26 -0700795 boolean alreadyPresent = false;
796 for (int i = 0, N = authority.periodicSyncs.size(); i < N; i++) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700797 PeriodicSync syncInfo = authority.periodicSyncs.get(i);
798 if (PeriodicSync.syncExtrasEquals(
799 toUpdate.extras,
800 syncInfo.extras)) {
801 if (toUpdate.period == syncInfo.period &&
802 toUpdate.flexTime == syncInfo.flexTime) {
803 // Absolutely the same.
Fred Quintana77c560f2010-03-29 22:20:26 -0700804 return;
805 }
Matthew Williamsfa774182013-06-18 15:44:11 -0700806 authority.periodicSyncs.set(i, new PeriodicSync(toUpdate));
Fred Quintana77c560f2010-03-29 22:20:26 -0700807 alreadyPresent = true;
808 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800809 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700810 }
Matthew Williamsfa774182013-06-18 15:44:11 -0700811 // If we added an entry to the periodicSyncs array also add an entry to
812 // the periodic syncs status to correspond to it.
Fred Quintana77c560f2010-03-29 22:20:26 -0700813 if (!alreadyPresent) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700814 authority.periodicSyncs.add(new PeriodicSync(toUpdate));
Fred Quintana77c560f2010-03-29 22:20:26 -0700815 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Matthew Williamsba352712013-08-13 15:53:31 -0700816 status.setPeriodicSyncTime(authority.periodicSyncs.size() - 1, 0L);
Fred Quintana77c560f2010-03-29 22:20:26 -0700817 }
818 } else {
Matthew Williamsfa774182013-06-18 15:44:11 -0700819 // Remove any periodic syncs that match the authority and extras.
Fred Quintana77c560f2010-03-29 22:20:26 -0700820 SyncStatusInfo status = mSyncStatus.get(authority.ident);
821 boolean changed = false;
Matthew Williamsfa774182013-06-18 15:44:11 -0700822 Iterator<PeriodicSync> iterator = authority.periodicSyncs.iterator();
Fred Quintana77c560f2010-03-29 22:20:26 -0700823 int i = 0;
824 while (iterator.hasNext()) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700825 PeriodicSync syncInfo = iterator.next();
826 if (PeriodicSync.syncExtrasEquals(syncInfo.extras, toUpdate.extras)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700827 iterator.remove();
828 changed = true;
Matthew Williamsfa774182013-06-18 15:44:11 -0700829 // If we removed an entry from the periodicSyncs array also
Fred Quintana77c560f2010-03-29 22:20:26 -0700830 // remove the corresponding entry from the status
831 if (status != null) {
832 status.removePeriodicSyncTime(i);
Matthew Williamsfa774182013-06-18 15:44:11 -0700833 } else {
Matthew Williamsba352712013-08-13 15:53:31 -0700834 Log.e(TAG, "Tried removing sync status on remove periodic sync but"
835 + "did not find it.");
Fred Quintana77c560f2010-03-29 22:20:26 -0700836 }
837 } else {
838 i++;
839 }
840 }
841 if (!changed) {
842 return;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800843 }
844 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700845 } finally {
846 writeAccountInfoLocked();
847 writeStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800848 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800849 }
850
851 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
852 }
853
Matthew Williamsfa774182013-06-18 15:44:11 -0700854 public void addPeriodicSync(PeriodicSync toAdd, int userId) {
855 updateOrRemovePeriodicSync(toAdd, userId, true /* add */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800856 }
857
Matthew Williamsfa774182013-06-18 15:44:11 -0700858 public void removePeriodicSync(PeriodicSync toRemove, int userId) {
859 updateOrRemovePeriodicSync(toRemove, userId, false /* remove */);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800860 }
861
Amith Yamasani04e0d262012-02-14 11:50:53 -0800862 public List<PeriodicSync> getPeriodicSyncs(Account account, int userId, String providerName) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800863 ArrayList<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
864 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800865 AuthorityInfo authority = getAuthorityLocked(account, userId, providerName,
866 "getPeriodicSyncs");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800867 if (authority != null) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700868 for (PeriodicSync item : authority.periodicSyncs) {
869 // Copy and send out. Necessary for thread-safety although it's parceled.
870 syncs.add(new PeriodicSync(item));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800871 }
872 }
873 }
874 return syncs;
875 }
876
Amith Yamasani04e0d262012-02-14 11:50:53 -0800877 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700878 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800879 Boolean auto = mMasterSyncAutomatically.get(userId);
880 if (auto != null && (boolean) auto == flag) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700881 return;
882 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800883 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700884 writeAccountInfoLocked();
885 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700886 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700887 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
888 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700889 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700890 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800891 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893
Amith Yamasani04e0d262012-02-14 11:50:53 -0800894 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700895 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800896 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800897 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700898 }
899 }
Costin Manolache360e4542009-09-04 13:36:04 -0700900
Amith Yamasani04e0d262012-02-14 11:50:53 -0800901 public void removeAuthority(Account account, int userId, String authority) {
Fred Quintana7620f1a2010-03-16 15:58:44 -0700902 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800903 removeAuthorityLocked(account, userId, authority, true /* doWrite */);
Fred Quintana7620f1a2010-03-16 15:58:44 -0700904 }
905 }
906
Dianne Hackborn231cc602009-04-27 17:10:36 -0700907 public AuthorityInfo getAuthority(int authorityId) {
908 synchronized (mAuthorities) {
909 return mAuthorities.get(authorityId);
910 }
911 }
Costin Manolache360e4542009-09-04 13:36:04 -0700912
Dianne Hackborn231cc602009-04-27 17:10:36 -0700913 /**
914 * Returns true if there is currently a sync operation for the given
Fred Quintana918339a2010-10-05 14:00:39 -0700915 * account or authority actively being processed.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700916 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800917 public boolean isSyncActive(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700918 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800919 for (SyncInfo syncInfo : getCurrentSyncs(userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700920 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700921 if (ainfo != null && ainfo.account.equals(account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800922 && ainfo.authority.equals(authority)
923 && ainfo.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700924 return true;
925 }
926 }
927 }
Costin Manolache360e4542009-09-04 13:36:04 -0700928
Dianne Hackborn231cc602009-04-27 17:10:36 -0700929 return false;
930 }
Costin Manolache360e4542009-09-04 13:36:04 -0700931
Dianne Hackborn231cc602009-04-27 17:10:36 -0700932 public PendingOperation insertIntoPending(PendingOperation op) {
933 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800934 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700935 Log.v(TAG, "insertIntoPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800936 + " user=" + op.userId
937 + " auth=" + op.authority
938 + " src=" + op.syncSource
939 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700940 }
Costin Manolache360e4542009-09-04 13:36:04 -0700941
Amith Yamasani04e0d262012-02-14 11:50:53 -0800942 AuthorityInfo authority = getOrCreateAuthorityLocked(op.account, op.userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700943 op.authority,
944 -1 /* desired identifier */,
945 true /* write accounts to storage */);
946 if (authority == null) {
947 return null;
948 }
Costin Manolache360e4542009-09-04 13:36:04 -0700949
Dianne Hackborn231cc602009-04-27 17:10:36 -0700950 op = new PendingOperation(op);
951 op.authorityId = authority.ident;
952 mPendingOperations.add(op);
Matthew Williamsba352712013-08-13 15:53:31 -0700953 appendPendingOperationLocked(op);
Costin Manolache360e4542009-09-04 13:36:04 -0700954
Dianne Hackborn231cc602009-04-27 17:10:36 -0700955 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
956 status.pending = true;
957 }
Costin Manolache360e4542009-09-04 13:36:04 -0700958
Fred Quintanaac9385e2009-06-22 18:00:59 -0700959 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700960 return op;
961 }
962
Matthew Williamsfa774182013-06-18 15:44:11 -0700963 /**
964 * Remove from list of pending operations. If successful, search through list for matching
965 * authorities. If there are no more pending syncs for the same authority/account/userid,
966 * update the SyncStatusInfo for that authority(authority here is the internal representation
967 * of a 'sync operation'.
968 * @param op
969 * @return
970 */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700971 public boolean deleteFromPending(PendingOperation op) {
972 boolean res = false;
973 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800974 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700975 Log.v(TAG, "deleteFromPending: account=" + op.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800976 + " user=" + op.userId
Dianne Hackborn231cc602009-04-27 17:10:36 -0700977 + " auth=" + op.authority
978 + " src=" + op.syncSource
979 + " extras=" + op.extras);
Fred Quintana77c560f2010-03-29 22:20:26 -0700980 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700981 if (mPendingOperations.remove(op)) {
982 if (mPendingOperations.size() == 0
983 || mNumPendingFinished >= PENDING_FINISH_TO_WRITE) {
984 writePendingOperationsLocked();
985 mNumPendingFinished = 0;
986 } else {
987 mNumPendingFinished++;
988 }
Costin Manolache360e4542009-09-04 13:36:04 -0700989
Amith Yamasani04e0d262012-02-14 11:50:53 -0800990 AuthorityInfo authority = getAuthorityLocked(op.account, op.userId, op.authority,
Dianne Hackborn231cc602009-04-27 17:10:36 -0700991 "deleteFromPending");
992 if (authority != null) {
Matthew Williamsfa774182013-06-18 15:44:11 -0700993 if (DEBUG) Log.v(TAG, "removing - " + authority.toString());
Dianne Hackborn231cc602009-04-27 17:10:36 -0700994 final int N = mPendingOperations.size();
995 boolean morePending = false;
996 for (int i=0; i<N; i++) {
997 PendingOperation cur = mPendingOperations.get(i);
998 if (cur.account.equals(op.account)
Amith Yamasani04e0d262012-02-14 11:50:53 -0800999 && cur.authority.equals(op.authority)
1000 && cur.userId == op.userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001001 morePending = true;
1002 break;
1003 }
1004 }
Costin Manolache360e4542009-09-04 13:36:04 -07001005
Dianne Hackborn231cc602009-04-27 17:10:36 -07001006 if (!morePending) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001007 if (DEBUG) Log.v(TAG, "no more pending!");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001008 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
1009 status.pending = false;
1010 }
1011 }
Costin Manolache360e4542009-09-04 13:36:04 -07001012
Dianne Hackborn231cc602009-04-27 17:10:36 -07001013 res = true;
1014 }
1015 }
Costin Manolache360e4542009-09-04 13:36:04 -07001016
Fred Quintanaac9385e2009-06-22 18:00:59 -07001017 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001018 return res;
1019 }
1020
Dianne Hackborn231cc602009-04-27 17:10:36 -07001021 /**
1022 * Return a copy of the current array of pending operations. The
1023 * PendingOperation objects are the real objects stored inside, so that
1024 * they can be used with deleteFromPending().
1025 */
1026 public ArrayList<PendingOperation> getPendingOperations() {
1027 synchronized (mAuthorities) {
1028 return new ArrayList<PendingOperation>(mPendingOperations);
1029 }
1030 }
Costin Manolache360e4542009-09-04 13:36:04 -07001031
Dianne Hackborn231cc602009-04-27 17:10:36 -07001032 /**
1033 * Return the number of currently pending operations.
1034 */
1035 public int getPendingOperationCount() {
1036 synchronized (mAuthorities) {
1037 return mPendingOperations.size();
1038 }
1039 }
Costin Manolache360e4542009-09-04 13:36:04 -07001040
Dianne Hackborn231cc602009-04-27 17:10:36 -07001041 /**
1042 * Called when the set of account has changed, given the new array of
1043 * active accounts.
1044 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001045 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001046 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001047 if (DEBUG) Log.v(TAG, "Updating for new accounts...");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001048 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1049 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1050 while (accIt.hasNext()) {
1051 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001052 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
1053 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001054 // This account no longer exists...
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001055 if (DEBUG) {
1056 Log.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001057 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001058 for (AuthorityInfo auth : acc.authorities.values()) {
1059 removing.put(auth.ident, auth);
1060 }
1061 accIt.remove();
1062 }
1063 }
Costin Manolache360e4542009-09-04 13:36:04 -07001064
Dianne Hackborn231cc602009-04-27 17:10:36 -07001065 // Clean out all data structures.
1066 int i = removing.size();
1067 if (i > 0) {
1068 while (i > 0) {
1069 i--;
1070 int ident = removing.keyAt(i);
1071 mAuthorities.remove(ident);
1072 int j = mSyncStatus.size();
1073 while (j > 0) {
1074 j--;
1075 if (mSyncStatus.keyAt(j) == ident) {
1076 mSyncStatus.remove(mSyncStatus.keyAt(j));
1077 }
1078 }
1079 j = mSyncHistory.size();
1080 while (j > 0) {
1081 j--;
1082 if (mSyncHistory.get(j).authorityId == ident) {
1083 mSyncHistory.remove(j);
1084 }
1085 }
1086 }
1087 writeAccountInfoLocked();
1088 writeStatusLocked();
1089 writePendingOperationsLocked();
1090 writeStatisticsLocked();
1091 }
1092 }
1093 }
1094
1095 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001096 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1097 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001098 */
Fred Quintana918339a2010-10-05 14:00:39 -07001099 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1100 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001101 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001102 if (DEBUG) {
Fred Quintana918339a2010-10-05 14:00:39 -07001103 Log.v(TAG, "setActiveSync: account="
1104 + activeSyncContext.mSyncOperation.account
1105 + " auth=" + activeSyncContext.mSyncOperation.authority
1106 + " src=" + activeSyncContext.mSyncOperation.syncSource
1107 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001108 }
Fred Quintana918339a2010-10-05 14:00:39 -07001109 AuthorityInfo authority = getOrCreateAuthorityLocked(
1110 activeSyncContext.mSyncOperation.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001111 activeSyncContext.mSyncOperation.userId,
Fred Quintana918339a2010-10-05 14:00:39 -07001112 activeSyncContext.mSyncOperation.authority,
1113 -1 /* assign a new identifier if creating a new authority */,
1114 true /* write to storage if this results in a change */);
1115 syncInfo = new SyncInfo(authority.ident,
1116 authority.account, authority.authority,
1117 activeSyncContext.mStartTime);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001118 getCurrentSyncs(authority.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001119 }
Costin Manolache360e4542009-09-04 13:36:04 -07001120
Fred Quintana918339a2010-10-05 14:00:39 -07001121 reportActiveChange();
1122 return syncInfo;
1123 }
1124
1125 /**
1126 * Called to indicate that a previously active sync is no longer active.
1127 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001128 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001129 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001130 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001131 Log.v(TAG, "removeActiveSync: account=" + syncInfo.account
1132 + " user=" + userId
1133 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001134 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001135 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001136 }
1137
1138 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001139 }
1140
1141 /**
1142 * To allow others to send active change reports, to poke clients.
1143 */
1144 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001145 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001146 }
Costin Manolache360e4542009-09-04 13:36:04 -07001147
Dianne Hackborn231cc602009-04-27 17:10:36 -07001148 /**
1149 * Note that sync has started for the given account and authority.
1150 */
Alon Albert57286f92012-10-09 14:21:38 -07001151 public long insertStartSyncEvent(Account accountName, int userId, int reason,
1152 String authorityName, long now, int source, boolean initialization, Bundle extras) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001153 long id;
1154 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001155 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001156 Log.v(TAG, "insertStartSyncEvent: account=" + accountName + "user=" + userId
Dianne Hackborn231cc602009-04-27 17:10:36 -07001157 + " auth=" + authorityName + " source=" + source);
Fred Quintana77c560f2010-03-29 22:20:26 -07001158 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001159 AuthorityInfo authority = getAuthorityLocked(accountName, userId, authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001160 "insertStartSyncEvent");
1161 if (authority == null) {
1162 return -1;
1163 }
1164 SyncHistoryItem item = new SyncHistoryItem();
Fred Quintanadc475562012-05-04 15:51:54 -07001165 item.initialization = initialization;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001166 item.authorityId = authority.ident;
1167 item.historyId = mNextHistoryId++;
1168 if (mNextHistoryId < 0) mNextHistoryId = 0;
1169 item.eventTime = now;
1170 item.source = source;
Alon Albert57286f92012-10-09 14:21:38 -07001171 item.reason = reason;
1172 item.extras = extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001173 item.event = EVENT_START;
1174 mSyncHistory.add(0, item);
1175 while (mSyncHistory.size() > MAX_HISTORY) {
1176 mSyncHistory.remove(mSyncHistory.size()-1);
1177 }
1178 id = item.historyId;
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001179 if (DEBUG) Log.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001180 }
Costin Manolache360e4542009-09-04 13:36:04 -07001181
Fred Quintanaac9385e2009-06-22 18:00:59 -07001182 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001183 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
1185
Fred Quintana77c560f2010-03-29 22:20:26 -07001186 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001188 synchronized (mAuthorities) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001189 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001190 Log.v(TAG, "stopSyncEvent: historyId=" + historyId);
1191 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001192 SyncHistoryItem item = null;
1193 int i = mSyncHistory.size();
1194 while (i > 0) {
1195 i--;
1196 item = mSyncHistory.get(i);
1197 if (item.historyId == historyId) {
1198 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001200 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 }
Costin Manolache360e4542009-09-04 13:36:04 -07001202
Dianne Hackborn231cc602009-04-27 17:10:36 -07001203 if (item == null) {
1204 Log.w(TAG, "stopSyncEvent: no history for id " + historyId);
1205 return;
1206 }
Costin Manolache360e4542009-09-04 13:36:04 -07001207
Dianne Hackborn231cc602009-04-27 17:10:36 -07001208 item.elapsedTime = elapsedTime;
1209 item.event = EVENT_STOP;
1210 item.mesg = resultMessage;
1211 item.downstreamActivity = downstreamActivity;
1212 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001213
Dianne Hackborn231cc602009-04-27 17:10:36 -07001214 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001215
Dianne Hackborn231cc602009-04-27 17:10:36 -07001216 status.numSyncs++;
1217 status.totalElapsedTime += elapsedTime;
1218 switch (item.source) {
1219 case SOURCE_LOCAL:
1220 status.numSourceLocal++;
1221 break;
1222 case SOURCE_POLL:
1223 status.numSourcePoll++;
1224 break;
1225 case SOURCE_USER:
1226 status.numSourceUser++;
1227 break;
1228 case SOURCE_SERVER:
1229 status.numSourceServer++;
1230 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001231 case SOURCE_PERIODIC:
1232 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001233 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001234 }
Costin Manolache360e4542009-09-04 13:36:04 -07001235
Dianne Hackborn231cc602009-04-27 17:10:36 -07001236 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001237 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001238 if (mDayStats[0] == null) {
1239 mDayStats[0] = new DayStats(day);
1240 } else if (day != mDayStats[0].day) {
1241 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1242 mDayStats[0] = new DayStats(day);
1243 writeStatisticsNow = true;
1244 } else if (mDayStats[0] == null) {
1245 }
1246 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001247
Dianne Hackborn231cc602009-04-27 17:10:36 -07001248 final long lastSyncTime = (item.eventTime + elapsedTime);
1249 boolean writeStatusNow = false;
1250 if (MESG_SUCCESS.equals(resultMessage)) {
1251 // - if successful, update the successful columns
1252 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1253 writeStatusNow = true;
1254 }
1255 status.lastSuccessTime = lastSyncTime;
1256 status.lastSuccessSource = item.source;
1257 status.lastFailureTime = 0;
1258 status.lastFailureSource = -1;
1259 status.lastFailureMesg = null;
1260 status.initialFailureTime = 0;
1261 ds.successCount++;
1262 ds.successTime += elapsedTime;
1263 } else if (!MESG_CANCELED.equals(resultMessage)) {
1264 if (status.lastFailureTime == 0) {
1265 writeStatusNow = true;
1266 }
1267 status.lastFailureTime = lastSyncTime;
1268 status.lastFailureSource = item.source;
1269 status.lastFailureMesg = resultMessage;
1270 if (status.initialFailureTime == 0) {
1271 status.initialFailureTime = lastSyncTime;
1272 }
1273 ds.failureCount++;
1274 ds.failureTime += elapsedTime;
1275 }
Costin Manolache360e4542009-09-04 13:36:04 -07001276
Dianne Hackborn231cc602009-04-27 17:10:36 -07001277 if (writeStatusNow) {
1278 writeStatusLocked();
1279 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1280 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1281 WRITE_STATUS_DELAY);
1282 }
1283 if (writeStatisticsNow) {
1284 writeStatisticsLocked();
1285 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1286 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1287 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001288 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001289 }
Costin Manolache360e4542009-09-04 13:36:04 -07001290
Fred Quintanaac9385e2009-06-22 18:00:59 -07001291 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001292 }
1293
1294 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001295 * Return a list of the currently active syncs. Note that the returned items are the
1296 * real, live active sync objects, so be careful what you do with it.
1297 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001298 public List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001299 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001300 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1301 if (syncs == null) {
1302 syncs = new ArrayList<SyncInfo>();
1303 mCurrentSyncs.put(userId, syncs);
1304 }
Amith Yamasani1b6ae002012-03-14 14:53:36 -07001305 return syncs;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001306 }
1307 }
Costin Manolache360e4542009-09-04 13:36:04 -07001308
Dianne Hackborn231cc602009-04-27 17:10:36 -07001309 /**
1310 * Return an array of the current sync status for all authorities. Note
1311 * that the objects inside the array are the real, live status objects,
1312 * so be careful what you do with them.
1313 */
1314 public ArrayList<SyncStatusInfo> getSyncStatus() {
1315 synchronized (mAuthorities) {
1316 final int N = mSyncStatus.size();
1317 ArrayList<SyncStatusInfo> ops = new ArrayList<SyncStatusInfo>(N);
1318 for (int i=0; i<N; i++) {
1319 ops.add(mSyncStatus.valueAt(i));
1320 }
1321 return ops;
1322 }
1323 }
Costin Manolache360e4542009-09-04 13:36:04 -07001324
Dianne Hackborn231cc602009-04-27 17:10:36 -07001325 /**
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001326 * Return a copy of the specified authority with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001327 */
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001328 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(
1329 Account account, int userId, String authority) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001330 synchronized (mAuthorities) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001331 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(account, userId, authority,
1332 -1 /* assign a new identifier if creating a new authority */,
1333 true /* write to storage if this results in a change */);
1334 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1335 }
1336 }
1337
1338 /**
1339 * Return a copy of all authorities with their corresponding sync status
1340 */
1341 public ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> getCopyOfAllAuthoritiesWithSyncStatus() {
1342 synchronized (mAuthorities) {
1343 ArrayList<Pair<AuthorityInfo, SyncStatusInfo>> infos =
1344 new ArrayList<Pair<AuthorityInfo, SyncStatusInfo>>(mAuthorities.size());
1345 for (int i = 0; i < mAuthorities.size(); i++) {
1346 infos.add(createCopyPairOfAuthorityWithSyncStatusLocked(mAuthorities.valueAt(i)));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001347 }
1348 return infos;
1349 }
1350 }
1351
1352 /**
Costin Manolacheb7520982009-09-02 18:03:05 -07001353 * Returns the status that matches the authority and account.
1354 *
1355 * @param account the account we want to check
Dianne Hackborn231cc602009-04-27 17:10:36 -07001356 * @param authority the authority whose row should be selected
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001357 * @return the SyncStatusInfo for the authority
Dianne Hackborn231cc602009-04-27 17:10:36 -07001358 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001359 public SyncStatusInfo getStatusByAccountAndAuthority(Account account, int userId,
1360 String authority) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001361 if (account == null || authority == null) {
1362 throw new IllegalArgumentException();
1363 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001364 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001365 final int N = mSyncStatus.size();
1366 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001367 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001368 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Costin Manolacheb7520982009-09-02 18:03:05 -07001369
Amith Yamasani04e0d262012-02-14 11:50:53 -08001370 if (ainfo != null && ainfo.authority.equals(authority)
1371 && ainfo.userId == userId
1372 && account.equals(ainfo.account)) {
Costin Manolacheb7520982009-09-02 18:03:05 -07001373 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001374 }
1375 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001376 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001377 }
1378 }
Costin Manolache360e4542009-09-04 13:36:04 -07001379
Dianne Hackborn231cc602009-04-27 17:10:36 -07001380 /**
1381 * Return true if the pending status is true of any matching authorities.
1382 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001383 public boolean isSyncPending(Account account, int userId, String authority) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001384 synchronized (mAuthorities) {
1385 final int N = mSyncStatus.size();
1386 for (int i=0; i<N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001387 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001388 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1389 if (ainfo == null) {
1390 continue;
1391 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001392 if (userId != ainfo.userId) {
1393 continue;
1394 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001395 if (account != null && !ainfo.account.equals(account)) {
1396 continue;
1397 }
1398 if (ainfo.authority.equals(authority) && cur.pending) {
1399 return true;
1400 }
1401 }
1402 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 }
1404 }
1405
1406 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001407 * Return an array of the current sync status for all authorities. Note
1408 * that the objects inside the array are the real, live status objects,
1409 * so be careful what you do with them.
1410 */
1411 public ArrayList<SyncHistoryItem> getSyncHistory() {
1412 synchronized (mAuthorities) {
1413 final int N = mSyncHistory.size();
1414 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1415 for (int i=0; i<N; i++) {
1416 items.add(mSyncHistory.get(i));
1417 }
1418 return items;
1419 }
1420 }
Costin Manolache360e4542009-09-04 13:36:04 -07001421
Dianne Hackborn231cc602009-04-27 17:10:36 -07001422 /**
1423 * Return an array of the current per-day statistics. Note
1424 * that the objects inside the array are the real, live status objects,
1425 * so be careful what you do with them.
1426 */
1427 public DayStats[] getDayStatistics() {
1428 synchronized (mAuthorities) {
1429 DayStats[] ds = new DayStats[mDayStats.length];
1430 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1431 return ds;
1432 }
1433 }
Costin Manolache360e4542009-09-04 13:36:04 -07001434
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001435 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1436 AuthorityInfo authorityInfo) {
1437 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1438 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1439 }
1440
Dianne Hackborn55280a92009-05-07 15:53:46 -07001441 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001442 mCal.setTimeInMillis(System.currentTimeMillis());
1443 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1444 if (mYear != mCal.get(Calendar.YEAR)) {
1445 mYear = mCal.get(Calendar.YEAR);
1446 mCal.clear();
1447 mCal.set(Calendar.YEAR, mYear);
1448 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1449 }
1450 return dayOfYear + mYearInDays;
1451 }
Costin Manolache360e4542009-09-04 13:36:04 -07001452
Dianne Hackborn231cc602009-04-27 17:10:36 -07001453 /**
1454 * Retrieve an authority, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001455 *
Dianne Hackborn231cc602009-04-27 17:10:36 -07001456 * @param accountName The name of the account for the authority.
1457 * @param authorityName The name of the authority itself.
1458 * @param tag If non-null, this will be used in a log message if the
1459 * requested authority does not exist.
1460 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001461 private AuthorityInfo getAuthorityLocked(Account accountName, int userId, String authorityName,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001462 String tag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001463 AccountAndUser au = new AccountAndUser(accountName, userId);
1464 AccountInfo accountInfo = mAccounts.get(au);
1465 if (accountInfo == null) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001466 if (tag != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001467 if (DEBUG) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001468 Log.v(TAG, tag + ": unknown account " + au);
Fred Quintanab763ab22009-08-18 18:07:30 -07001469 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001470 }
1471 return null;
1472 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001473 AuthorityInfo authority = accountInfo.authorities.get(authorityName);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001474 if (authority == null) {
1475 if (tag != null) {
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001476 if (DEBUG) {
Fred Quintanab763ab22009-08-18 18:07:30 -07001477 Log.v(TAG, tag + ": unknown authority " + authorityName);
1478 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001479 }
1480 return null;
1481 }
Costin Manolache360e4542009-09-04 13:36:04 -07001482
Dianne Hackborn231cc602009-04-27 17:10:36 -07001483 return authority;
1484 }
Costin Manolache360e4542009-09-04 13:36:04 -07001485
Matthew Williamsfa774182013-06-18 15:44:11 -07001486 /**
1487 * Retrieve an authority, returning null if one does not exist.
1488 *
1489 * @param service The service name used for this sync.
1490 * @param userId The user for whom this sync is scheduled.
1491 * @param tag If non-null, this will be used in a log message if the
1492 * requested authority does not exist.
1493 */
1494 private AuthorityInfo getAuthorityLocked(ComponentName service, int userId, String tag) {
1495 AuthorityInfo authority = mServices.get(service).get(userId);
1496 if (authority == null) {
1497 if (tag != null) {
1498 if (DEBUG) {
1499 Log.v(TAG, tag + " No authority info found for " + service + " for user "
1500 + userId);
1501 }
1502 }
1503 return null;
1504 }
1505 return authority;
1506 }
1507
1508 /**
1509 * @param cname identifier for the service.
1510 * @param userId for the syncs corresponding to this authority.
1511 * @param ident unique identifier for authority. -1 for none.
1512 * @param doWrite if true, update the accounts.xml file on the disk.
1513 * @return the authority that corresponds to the provided sync service, creating it if none
1514 * exists.
1515 */
1516 private AuthorityInfo getOrCreateAuthorityLocked(ComponentName cname, int userId, int ident,
1517 boolean doWrite) {
1518 SparseArray<AuthorityInfo> aInfo = mServices.get(cname);
1519 if (aInfo == null) {
1520 aInfo = new SparseArray<AuthorityInfo>();
1521 mServices.put(cname, aInfo);
1522 }
1523 AuthorityInfo authority = aInfo.get(userId);
1524 if (authority == null) {
1525 if (ident < 0) {
1526 ident = mNextAuthorityId;
1527 mNextAuthorityId++;
1528 doWrite = true;
1529 }
1530 if (DEBUG) {
1531 Log.v(TAG, "created a new AuthorityInfo for " + cname.getPackageName()
1532 + ", " + cname.getClassName()
1533 + ", user: " + userId);
1534 }
1535 authority = new AuthorityInfo(cname, userId, ident);
1536 aInfo.put(userId, authority);
1537 mAuthorities.put(ident, authority);
1538 if (doWrite) {
1539 writeAccountInfoLocked();
1540 }
1541 }
1542 return authority;
1543 }
1544
Amith Yamasani04e0d262012-02-14 11:50:53 -08001545 private AuthorityInfo getOrCreateAuthorityLocked(Account accountName, int userId,
Dianne Hackborn231cc602009-04-27 17:10:36 -07001546 String authorityName, int ident, boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001547 AccountAndUser au = new AccountAndUser(accountName, userId);
1548 AccountInfo account = mAccounts.get(au);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001549 if (account == null) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001550 account = new AccountInfo(au);
1551 mAccounts.put(au, account);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001552 }
1553 AuthorityInfo authority = account.authorities.get(authorityName);
1554 if (authority == null) {
1555 if (ident < 0) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001556 ident = mNextAuthorityId;
1557 mNextAuthorityId++;
1558 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001559 }
Dianne Hackborn40e9f292012-11-27 19:12:23 -08001560 if (DEBUG) {
Fred Quintana77c560f2010-03-29 22:20:26 -07001561 Log.v(TAG, "created a new AuthorityInfo for " + accountName
Amith Yamasani04e0d262012-02-14 11:50:53 -08001562 + ", user " + userId
1563 + ", provider " + authorityName);
Fred Quintana77c560f2010-03-29 22:20:26 -07001564 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001565 authority = new AuthorityInfo(accountName, userId, authorityName, ident);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001566 account.authorities.put(authorityName, authority);
1567 mAuthorities.put(ident, authority);
1568 if (doWrite) {
1569 writeAccountInfoLocked();
1570 }
1571 }
Costin Manolache360e4542009-09-04 13:36:04 -07001572
Dianne Hackborn231cc602009-04-27 17:10:36 -07001573 return authority;
1574 }
Costin Manolache360e4542009-09-04 13:36:04 -07001575
Amith Yamasani04e0d262012-02-14 11:50:53 -08001576 private void removeAuthorityLocked(Account account, int userId, String authorityName,
1577 boolean doWrite) {
1578 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001579 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001580 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1581 if (authorityInfo != null) {
1582 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001583 if (doWrite) {
1584 writeAccountInfoLocked();
1585 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001586 }
1587 }
1588 }
1589
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001590 /**
1591 * Updates (in a synchronized way) the periodic sync time of the specified
1592 * authority id and target periodic sync
1593 */
1594 public void setPeriodicSyncTime(
Matthew Williamsfa774182013-06-18 15:44:11 -07001595 int authorityId, PeriodicSync targetPeriodicSync, long when) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001596 boolean found = false;
1597 final AuthorityInfo authorityInfo;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001598 synchronized (mAuthorities) {
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001599 authorityInfo = mAuthorities.get(authorityId);
1600 for (int i = 0; i < authorityInfo.periodicSyncs.size(); i++) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001601 PeriodicSync periodicSync = authorityInfo.periodicSyncs.get(i);
1602 if (targetPeriodicSync.equals(periodicSync)) {
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001603 mSyncStatus.get(authorityId).setPeriodicSyncTime(i, when);
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001604 found = true;
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001605 break;
1606 }
1607 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001608 }
Georgi Nikolov44c4ddf2013-06-28 14:12:09 -07001609 if (!found) {
1610 Log.w(TAG, "Ignoring setPeriodicSyncTime request for a sync that does not exist. " +
1611 "Authority: " + authorityInfo.authority);
1612 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001613 }
1614
Dianne Hackborn231cc602009-04-27 17:10:36 -07001615 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1616 SyncStatusInfo status = mSyncStatus.get(authorityId);
1617 if (status == null) {
1618 status = new SyncStatusInfo(authorityId);
1619 mSyncStatus.put(authorityId, status);
1620 }
1621 return status;
1622 }
Costin Manolache360e4542009-09-04 13:36:04 -07001623
Dianne Hackborn55280a92009-05-07 15:53:46 -07001624 public void writeAllState() {
1625 synchronized (mAuthorities) {
1626 // Account info is always written so no need to do it here.
Costin Manolache360e4542009-09-04 13:36:04 -07001627
Dianne Hackborn55280a92009-05-07 15:53:46 -07001628 if (mNumPendingFinished > 0) {
1629 // Only write these if they are out of date.
1630 writePendingOperationsLocked();
1631 }
Costin Manolache360e4542009-09-04 13:36:04 -07001632
Dianne Hackborn55280a92009-05-07 15:53:46 -07001633 // Just always write these... they are likely out of date.
1634 writeStatusLocked();
1635 writeStatisticsLocked();
1636 }
1637 }
Costin Manolache360e4542009-09-04 13:36:04 -07001638
Dianne Hackborn231cc602009-04-27 17:10:36 -07001639 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001640 * public for testing
1641 */
1642 public void clearAndReadState() {
1643 synchronized (mAuthorities) {
1644 mAuthorities.clear();
1645 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001646 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001647 mPendingOperations.clear();
1648 mSyncStatus.clear();
1649 mSyncHistory.clear();
1650
1651 readAccountInfoLocked();
1652 readStatusLocked();
1653 readPendingOperationsLocked();
1654 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001655 readAndDeleteLegacyAccountInfoLocked();
1656 writeAccountInfoLocked();
1657 writeStatusLocked();
1658 writePendingOperationsLocked();
1659 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001660 }
1661 }
1662
1663 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001664 * Read all account information back in to the initial engine state.
1665 */
1666 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001667 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001668 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001670 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001671 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
1672 Log.v(TAG, "Reading " + mAccountInfoFile.getBaseFile());
1673 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001674 XmlPullParser parser = Xml.newPullParser();
1675 parser.setInput(fis, null);
1676 int eventType = parser.getEventType();
1677 while (eventType != XmlPullParser.START_TAG) {
1678 eventType = parser.next();
1679 }
1680 String tagName = parser.getName();
1681 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001682 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001683 String versionString = parser.getAttributeValue(null, "version");
1684 int version;
1685 try {
1686 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1687 } catch (NumberFormatException e) {
1688 version = 0;
1689 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001690 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001691 try {
1692 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1693 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1694 } catch (NumberFormatException e) {
1695 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001696 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001697 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1698 try {
1699 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1700 } catch (NumberFormatException e) {
1701 mSyncRandomOffset = 0;
1702 }
1703 if (mSyncRandomOffset == 0) {
1704 Random random = new Random(System.currentTimeMillis());
1705 mSyncRandomOffset = random.nextInt(86400);
1706 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001707 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001708 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001709 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001710 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001711 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001712 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001713 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001714 if (parser.getDepth() == 2) {
1715 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001716 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001717 periodicSync = null;
Fred Quintana77c560f2010-03-29 22:20:26 -07001718 if (authority.ident > highestAuthorityId) {
1719 highestAuthorityId = authority.ident;
1720 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001721 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1722 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001723 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001724 } else if (parser.getDepth() == 3) {
1725 if ("periodicSync".equals(tagName) && authority != null) {
1726 periodicSync = parsePeriodicSync(parser, authority);
1727 }
1728 } else if (parser.getDepth() == 4 && periodicSync != null) {
1729 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001730 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001731 }
1732 }
1733 }
1734 eventType = parser.next();
1735 } while (eventType != XmlPullParser.END_DOCUMENT);
1736 }
1737 } catch (XmlPullParserException e) {
1738 Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001739 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001740 } catch (java.io.IOException e) {
1741 if (fis == null) Log.i(TAG, "No initial accounts");
1742 else Log.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001743 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001744 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001745 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001746 if (fis != null) {
1747 try {
1748 fis.close();
1749 } catch (java.io.IOException e1) {
1750 }
1751 }
1752 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001753
Fred Quintana77c560f2010-03-29 22:20:26 -07001754 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001755 }
Costin Manolache360e4542009-09-04 13:36:04 -07001756
Fred Quintanafb084402010-03-23 17:57:03 -07001757 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001758 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1759 * pending.xml was used starting in KLP.
1760 * @param syncDir directory where the sync files are located.
1761 */
1762 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1763 File file = new File(syncDir, "pending.bin");
1764 if (!file.exists()) {
1765 return;
1766 } else {
1767 file.delete();
1768 }
1769 }
1770
1771 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001772 * some authority names have changed. copy over their settings and delete the old ones
1773 * @return true if a change was made
1774 */
1775 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1776 boolean writeNeeded = false;
1777
1778 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1779 final int N = mAuthorities.size();
1780 for (int i=0; i<N; i++) {
1781 AuthorityInfo authority = mAuthorities.valueAt(i);
1782 // skip this authority if it isn't one of the renamed ones
1783 final String newAuthorityName = sAuthorityRenames.get(authority.authority);
1784 if (newAuthorityName == null) {
1785 continue;
1786 }
1787
1788 // remember this authority so we can remove it later. we can't remove it
1789 // now without messing up this loop iteration
1790 authoritiesToRemove.add(authority);
1791
1792 // this authority isn't enabled, no need to copy it to the new authority name since
1793 // the default is "disabled"
1794 if (!authority.enabled) {
1795 continue;
1796 }
1797
1798 // if we already have a record of this new authority then don't copy over the settings
Amith Yamasani04e0d262012-02-14 11:50:53 -08001799 if (getAuthorityLocked(authority.account, authority.userId, newAuthorityName, "cleanup")
1800 != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001801 continue;
1802 }
1803
1804 AuthorityInfo newAuthority = getOrCreateAuthorityLocked(authority.account,
Amith Yamasani04e0d262012-02-14 11:50:53 -08001805 authority.userId, newAuthorityName, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001806 newAuthority.enabled = true;
1807 writeNeeded = true;
1808 }
1809
1810 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001811 removeAuthorityLocked(authorityInfo.account, authorityInfo.userId,
1812 authorityInfo.authority, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001813 writeNeeded = true;
1814 }
1815
1816 return writeNeeded;
1817 }
1818
Amith Yamasani04e0d262012-02-14 11:50:53 -08001819 private void parseListenForTickles(XmlPullParser parser) {
1820 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1821 int userId = 0;
1822 try {
1823 userId = Integer.parseInt(user);
1824 } catch (NumberFormatException e) {
1825 Log.e(TAG, "error parsing the user for listen-for-tickles", e);
1826 } catch (NullPointerException e) {
1827 Log.e(TAG, "the user in listen-for-tickles is null", e);
1828 }
1829 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1830 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1831 mMasterSyncAutomatically.put(userId, listen);
1832 }
1833
Fred Quintanac2e46912010-03-15 16:10:44 -07001834 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001835 AuthorityInfo authority = null;
1836 int id = -1;
1837 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001838 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001839 } catch (NumberFormatException e) {
1840 Log.e(TAG, "error parsing the id of the authority", e);
1841 } catch (NullPointerException e) {
1842 Log.e(TAG, "the id of the authority is null", e);
1843 }
1844 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001845 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001846 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001847 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001848 String accountName = parser.getAttributeValue(null, "account");
1849 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001850 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001851 String packageName = parser.getAttributeValue(null, "package");
1852 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001853 int userId = user == null ? 0 : Integer.parseInt(user);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001854 if (accountType == null) {
1855 accountType = "com.google";
Fred Quintanafb084402010-03-23 17:57:03 -07001856 syncable = "unknown";
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001857 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001858 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001859 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
1860 Log.v(TAG, "Adding authority: account="
1861 + accountName + " auth=" + authorityName
1862 + " user=" + userId
1863 + " enabled=" + enabled
1864 + " syncable=" + syncable);
1865 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001866 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001867 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001868 Log.v(TAG, "Creating entry");
1869 }
1870 if (accountName != null && accountType != null) {
1871 authority = getOrCreateAuthorityLocked(
Matthew Williamsba352712013-08-13 15:53:31 -07001872 new Account(accountName, accountType), userId, authorityName, id,
1873 false);
Matthew Williamsfa774182013-06-18 15:44:11 -07001874 } else {
1875 authority = getOrCreateAuthorityLocked(
1876 new ComponentName(packageName, className), userId, id, false);
1877 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001878 // If the version is 0 then we are upgrading from a file format that did not
1879 // know about periodic syncs. In that case don't clear the list since we
Matthew Williamsfa774182013-06-18 15:44:11 -07001880 // want the default, which is a daily periodic sync.
Fred Quintanac2e46912010-03-15 16:10:44 -07001881 // Otherwise clear out this default list since we will populate it later with
1882 // the periodic sync descriptions that are read from the configuration file.
1883 if (version > 0) {
1884 authority.periodicSyncs.clear();
1885 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001886 }
1887 if (authority != null) {
1888 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
1889 if ("unknown".equals(syncable)) {
1890 authority.syncable = -1;
1891 } else {
1892 authority.syncable =
Fred Quintanafb084402010-03-23 17:57:03 -07001893 (syncable == null || Boolean.parseBoolean(syncable)) ? 1 : 0;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001894 }
1895 } else {
1896 Log.w(TAG, "Failure adding authority: account="
1897 + accountName + " auth=" + authorityName
1898 + " enabled=" + enabled
1899 + " syncable=" + syncable);
1900 }
1901 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001902 return authority;
1903 }
1904
Matthew Williamsfa774182013-06-18 15:44:11 -07001905 /**
1906 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1907 */
1908 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authority) {
1909 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001910 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001911 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001912 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001913 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001914 try {
1915 period = Long.parseLong(periodValue);
1916 } catch (NumberFormatException e) {
1917 Log.e(TAG, "error parsing the period of a periodic sync", e);
1918 return null;
1919 } catch (NullPointerException e) {
1920 Log.e(TAG, "the period of a periodic sync is null", e);
1921 return null;
1922 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001923 try {
1924 flextime = Long.parseLong(flexValue);
1925 } catch (NumberFormatException e) {
1926 Log.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue);
1927 flextime = calculateDefaultFlexTime(period);
1928 } catch (NullPointerException expected) {
1929 flextime = calculateDefaultFlexTime(period);
1930 Log.d(TAG, "No flex time specified for this sync, using a default. period: "
1931 + period + " flex: " + flextime);
1932 }
1933 final PeriodicSync periodicSync =
1934 new PeriodicSync(authority.account, authority.authority, extras,
1935 period, flextime);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001936 authority.periodicSyncs.add(periodicSync);
1937 return periodicSync;
1938 }
1939
Matthew Williamsfa774182013-06-18 15:44:11 -07001940 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001941 String name = parser.getAttributeValue(null, "name");
1942 String type = parser.getAttributeValue(null, "type");
1943 String value1 = parser.getAttributeValue(null, "value1");
1944 String value2 = parser.getAttributeValue(null, "value2");
1945
1946 try {
1947 if ("long".equals(type)) {
1948 extras.putLong(name, Long.parseLong(value1));
1949 } else if ("integer".equals(type)) {
1950 extras.putInt(name, Integer.parseInt(value1));
1951 } else if ("double".equals(type)) {
1952 extras.putDouble(name, Double.parseDouble(value1));
1953 } else if ("float".equals(type)) {
1954 extras.putFloat(name, Float.parseFloat(value1));
1955 } else if ("boolean".equals(type)) {
1956 extras.putBoolean(name, Boolean.parseBoolean(value1));
1957 } else if ("string".equals(type)) {
1958 extras.putString(name, value1);
1959 } else if ("account".equals(type)) {
1960 extras.putParcelable(name, new Account(value1, value2));
1961 }
1962 } catch (NumberFormatException e) {
1963 Log.e(TAG, "error parsing bundle value", e);
1964 } catch (NullPointerException e) {
1965 Log.e(TAG, "error parsing bundle value", e);
1966 }
1967 }
1968
Dianne Hackborn231cc602009-04-27 17:10:36 -07001969 /**
1970 * Write all account information to the account file.
1971 */
1972 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001973 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
1974 Log.v(TAG, "Writing new " + mAccountInfoFile.getBaseFile());
1975 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001976 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001977
Dianne Hackborn231cc602009-04-27 17:10:36 -07001978 try {
1979 fos = mAccountInfoFile.startWrite();
1980 XmlSerializer out = new FastXmlSerializer();
1981 out.setOutput(fos, "utf-8");
1982 out.startDocument(null, true);
1983 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001984
Dianne Hackborn231cc602009-04-27 17:10:36 -07001985 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001986 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001987 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001988 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001989
1990 // Write the Sync Automatically flags for each user
1991 final int M = mMasterSyncAutomatically.size();
1992 for (int m = 0; m < M; m++) {
1993 int userId = mMasterSyncAutomatically.keyAt(m);
1994 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1995 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1996 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1997 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1998 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001999 }
Costin Manolache360e4542009-09-04 13:36:04 -07002000
Dianne Hackborn231cc602009-04-27 17:10:36 -07002001 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07002002 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07002003 AuthorityInfo authority = mAuthorities.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002004 out.startTag(null, "authority");
2005 out.attribute(null, "id", Integer.toString(authority.ident));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002006 out.attribute(null, XML_ATTR_USER, Integer.toString(authority.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002007 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Matthew Williamsfa774182013-06-18 15:44:11 -07002008 if (authority.service == null) {
2009 out.attribute(null, "account", authority.account.name);
2010 out.attribute(null, "type", authority.account.type);
2011 out.attribute(null, "authority", authority.authority);
2012 } else {
2013 out.attribute(null, "package", authority.service.getPackageName());
2014 out.attribute(null, "class", authority.service.getClassName());
2015 }
Fred Quintana5e787c42009-08-16 23:13:53 -07002016 if (authority.syncable < 0) {
2017 out.attribute(null, "syncable", "unknown");
Fred Quintanafb084402010-03-23 17:57:03 -07002018 } else {
2019 out.attribute(null, "syncable", Boolean.toString(authority.syncable != 0));
Fred Quintana5e787c42009-08-16 23:13:53 -07002020 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002021 for (PeriodicSync periodicSync : authority.periodicSyncs) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002022 out.startTag(null, "periodicSync");
Matthew Williamsfa774182013-06-18 15:44:11 -07002023 out.attribute(null, "period", Long.toString(periodicSync.period));
2024 out.attribute(null, "flex", Long.toString(periodicSync.flexTime));
2025 final Bundle extras = periodicSync.extras;
2026 extrasToXml(out, extras);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002027 out.endTag(null, "periodicSync");
2028 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002029 out.endTag(null, "authority");
2030 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002031 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002032 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002033 mAccountInfoFile.finishWrite(fos);
2034 } catch (java.io.IOException e1) {
2035 Log.w(TAG, "Error writing accounts", e1);
2036 if (fos != null) {
2037 mAccountInfoFile.failWrite(fos);
2038 }
2039 }
2040 }
Costin Manolache360e4542009-09-04 13:36:04 -07002041
Dianne Hackborn231cc602009-04-27 17:10:36 -07002042 static int getIntColumn(Cursor c, String name) {
2043 return c.getInt(c.getColumnIndex(name));
2044 }
Costin Manolache360e4542009-09-04 13:36:04 -07002045
Dianne Hackborn231cc602009-04-27 17:10:36 -07002046 static long getLongColumn(Cursor c, String name) {
2047 return c.getLong(c.getColumnIndex(name));
2048 }
Costin Manolache360e4542009-09-04 13:36:04 -07002049
Dianne Hackborn231cc602009-04-27 17:10:36 -07002050 /**
2051 * Load sync engine state from the old syncmanager database, and then
2052 * erase it. Note that we don't deal with pending operations, active
2053 * sync, or history.
2054 */
Fred Quintana77c560f2010-03-29 22:20:26 -07002055 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002056 // Look for old database to initialize from.
2057 File file = mContext.getDatabasePath("syncmanager.db");
2058 if (!file.exists()) {
2059 return;
2060 }
2061 String path = file.getPath();
2062 SQLiteDatabase db = null;
2063 try {
2064 db = SQLiteDatabase.openDatabase(path, null,
2065 SQLiteDatabase.OPEN_READONLY);
2066 } catch (SQLiteException e) {
2067 }
Costin Manolache360e4542009-09-04 13:36:04 -07002068
Dianne Hackborn231cc602009-04-27 17:10:36 -07002069 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002070 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07002071
Dianne Hackborn231cc602009-04-27 17:10:36 -07002072 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07002073 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2074 Log.v(TAG, "Reading legacy sync accounts db");
2075 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002076 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
2077 qb.setTables("stats, status");
2078 HashMap<String,String> map = new HashMap<String,String>();
2079 map.put("_id", "status._id as _id");
2080 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002081 if (hasType) {
2082 map.put("account_type", "stats.account_type as account_type");
2083 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002084 map.put("authority", "stats.authority as authority");
2085 map.put("totalElapsedTime", "totalElapsedTime");
2086 map.put("numSyncs", "numSyncs");
2087 map.put("numSourceLocal", "numSourceLocal");
2088 map.put("numSourcePoll", "numSourcePoll");
2089 map.put("numSourceServer", "numSourceServer");
2090 map.put("numSourceUser", "numSourceUser");
2091 map.put("lastSuccessSource", "lastSuccessSource");
2092 map.put("lastSuccessTime", "lastSuccessTime");
2093 map.put("lastFailureSource", "lastFailureSource");
2094 map.put("lastFailureTime", "lastFailureTime");
2095 map.put("lastFailureMesg", "lastFailureMesg");
2096 map.put("pending", "pending");
2097 qb.setProjectionMap(map);
2098 qb.appendWhere("stats._id = status.stats_id");
2099 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002101 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002102 String accountType = hasType
2103 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07002104 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07002105 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002107 String authorityName = c.getString(c.getColumnIndex("authority"));
2108 AuthorityInfo authority = this.getOrCreateAuthorityLocked(
Amith Yamasani04e0d262012-02-14 11:50:53 -08002109 new Account(accountName, accountType), 0 /* legacy is single-user */,
Dianne Hackborn7a135592009-05-06 00:28:37 -07002110 authorityName, -1, false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002111 if (authority != null) {
2112 int i = mSyncStatus.size();
2113 boolean found = false;
2114 SyncStatusInfo st = null;
2115 while (i > 0) {
2116 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002117 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002118 if (st.authorityId == authority.ident) {
2119 found = true;
2120 break;
2121 }
2122 }
2123 if (!found) {
2124 st = new SyncStatusInfo(authority.ident);
2125 mSyncStatus.put(authority.ident, st);
2126 }
2127 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2128 st.numSyncs = getIntColumn(c, "numSyncs");
2129 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
2130 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
2131 st.numSourceServer = getIntColumn(c, "numSourceServer");
2132 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002133 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002134 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2135 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2136 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2137 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2138 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2139 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 }
Costin Manolache360e4542009-09-04 13:36:04 -07002142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002144
Dianne Hackborn231cc602009-04-27 17:10:36 -07002145 // Retrieve the settings.
2146 qb = new SQLiteQueryBuilder();
2147 qb.setTables("settings");
2148 c = qb.query(db, null, null, null, null, null, null);
2149 while (c.moveToNext()) {
2150 String name = c.getString(c.getColumnIndex("name"));
2151 String value = c.getString(c.getColumnIndex("value"));
2152 if (name == null) continue;
2153 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002154 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002155 } else if (name.startsWith("sync_provider_")) {
2156 String provider = name.substring("sync_provider_".length(),
2157 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002158 int i = mAuthorities.size();
2159 while (i > 0) {
2160 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002161 AuthorityInfo authority = mAuthorities.valueAt(i);
Fred Quintanaac9385e2009-06-22 18:00:59 -07002162 if (authority.authority.equals(provider)) {
2163 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002164 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002165 }
2166 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 }
Costin Manolache360e4542009-09-04 13:36:04 -07002169
Dianne Hackborn231cc602009-04-27 17:10:36 -07002170 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002171
Dianne Hackborn231cc602009-04-27 17:10:36 -07002172 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002173
Dianne Hackborn231cc602009-04-27 17:10:36 -07002174 (new File(path)).delete();
2175 }
2176 }
Costin Manolache360e4542009-09-04 13:36:04 -07002177
Dianne Hackborn231cc602009-04-27 17:10:36 -07002178 public static final int STATUS_FILE_END = 0;
2179 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002180
Dianne Hackborn231cc602009-04-27 17:10:36 -07002181 /**
2182 * Read all sync status back in to the initial engine state.
2183 */
2184 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002185 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2186 Log.v(TAG, "Reading " + mStatusFile.getBaseFile());
2187 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002188 try {
2189 byte[] data = mStatusFile.readFully();
2190 Parcel in = Parcel.obtain();
2191 in.unmarshall(data, 0, data.length);
2192 in.setDataPosition(0);
2193 int token;
2194 while ((token=in.readInt()) != STATUS_FILE_END) {
2195 if (token == STATUS_FILE_ITEM) {
2196 SyncStatusInfo status = new SyncStatusInfo(in);
2197 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2198 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002199 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2200 Log.v(TAG, "Adding status for id "
2201 + status.authorityId);
2202 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002203 mSyncStatus.put(status.authorityId, status);
2204 }
2205 } else {
2206 // Ooops.
2207 Log.w(TAG, "Unknown status token: " + token);
2208 break;
2209 }
2210 }
2211 } catch (java.io.IOException e) {
2212 Log.i(TAG, "No initial status");
2213 }
2214 }
Costin Manolache360e4542009-09-04 13:36:04 -07002215
Dianne Hackborn231cc602009-04-27 17:10:36 -07002216 /**
2217 * Write all sync status to the sync status file.
2218 */
2219 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002220 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2221 Log.v(TAG, "Writing new " + mStatusFile.getBaseFile());
2222 }
Costin Manolache360e4542009-09-04 13:36:04 -07002223
Dianne Hackborn231cc602009-04-27 17:10:36 -07002224 // The file is being written, so we don't need to have a scheduled
2225 // write until the next change.
2226 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002227
Dianne Hackborn231cc602009-04-27 17:10:36 -07002228 FileOutputStream fos = null;
2229 try {
2230 fos = mStatusFile.startWrite();
2231 Parcel out = Parcel.obtain();
2232 final int N = mSyncStatus.size();
2233 for (int i=0; i<N; i++) {
2234 SyncStatusInfo status = mSyncStatus.valueAt(i);
2235 out.writeInt(STATUS_FILE_ITEM);
2236 status.writeToParcel(out, 0);
2237 }
2238 out.writeInt(STATUS_FILE_END);
2239 fos.write(out.marshall());
2240 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002241
Dianne Hackborn231cc602009-04-27 17:10:36 -07002242 mStatusFile.finishWrite(fos);
2243 } catch (java.io.IOException e1) {
2244 Log.w(TAG, "Error writing status", e1);
2245 if (fos != null) {
2246 mStatusFile.failWrite(fos);
2247 }
2248 }
2249 }
Costin Manolache360e4542009-09-04 13:36:04 -07002250
Matthew Williamsba352712013-08-13 15:53:31 -07002251 public static final int PENDING_OPERATION_VERSION = 3;
Costin Manolache360e4542009-09-04 13:36:04 -07002252
Matthew Williamsba352712013-08-13 15:53:31 -07002253 /** Read all pending operations back in to the initial engine state. */
Dianne Hackborn231cc602009-04-27 17:10:36 -07002254 private void readPendingOperationsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002255 FileInputStream fis = null;
2256 if (!mPendingFile.getBaseFile().exists()) {
2257 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2258 Log.v(TAG_FILE, "No pending operation file.");
2259 return;
Matthew Williamsfa774182013-06-18 15:44:11 -07002260 }
2261 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002262 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07002263 fis = mPendingFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07002264 XmlPullParser parser;
2265 parser = Xml.newPullParser();
Matthew Williamsfa774182013-06-18 15:44:11 -07002266 parser.setInput(fis, null);
Matthew Williamsba352712013-08-13 15:53:31 -07002267
Matthew Williamsfa774182013-06-18 15:44:11 -07002268 int eventType = parser.getEventType();
2269 while (eventType != XmlPullParser.START_TAG &&
2270 eventType != XmlPullParser.END_DOCUMENT) {
2271 eventType = parser.next();
Matthew Williamsfa774182013-06-18 15:44:11 -07002272 }
Matthew Williamsba352712013-08-13 15:53:31 -07002273 if (eventType == XmlPullParser.END_DOCUMENT) return; // Nothing to read.
Matthew Williamsfa774182013-06-18 15:44:11 -07002274
2275 String tagName = parser.getName();
Matthew Williamsba352712013-08-13 15:53:31 -07002276 do {
Matthew Williamsfa774182013-06-18 15:44:11 -07002277 PendingOperation pop = null;
Matthew Williamsba352712013-08-13 15:53:31 -07002278 if (eventType == XmlPullParser.START_TAG) {
2279 try {
2280 tagName = parser.getName();
2281 if (parser.getDepth() == 1 && "op".equals(tagName)) {
2282 // Verify version.
2283 String versionString =
2284 parser.getAttributeValue(null, XML_ATTR_VERSION);
2285 if (versionString == null ||
2286 Integer.parseInt(versionString) != PENDING_OPERATION_VERSION) {
2287 Log.w(TAG, "Unknown pending operation version " + versionString);
2288 throw new java.io.IOException("Unknown version.");
2289 }
2290 int authorityId = Integer.valueOf(parser.getAttributeValue(
2291 null, XML_ATTR_AUTHORITYID));
2292 boolean expedited = Boolean.valueOf(parser.getAttributeValue(
2293 null, XML_ATTR_EXPEDITED));
2294 int syncSource = Integer.valueOf(parser.getAttributeValue(
2295 null, XML_ATTR_SOURCE));
2296 int reason = Integer.valueOf(parser.getAttributeValue(
2297 null, XML_ATTR_REASON));
2298 AuthorityInfo authority = mAuthorities.get(authorityId);
2299 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2300 Log.v(TAG_FILE, authorityId + " " + expedited + " " + syncSource + " "
2301 + reason);
2302 }
2303 if (authority != null) {
2304 pop = new PendingOperation(
2305 authority.account, authority.userId, reason,
2306 syncSource, authority.authority, new Bundle(),
2307 expedited);
2308 pop.flatExtras = null; // No longer used.
2309 mPendingOperations.add(pop);
2310 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2311 Log.v(TAG_FILE, "Adding pending op: "
2312 + pop.authority
Matthew Williamsfa774182013-06-18 15:44:11 -07002313 + " src=" + pop.syncSource
2314 + " reason=" + pop.reason
2315 + " expedited=" + pop.expedited);
Matthew Williamsfa774182013-06-18 15:44:11 -07002316 }
Matthew Williamsba352712013-08-13 15:53:31 -07002317 } else {
2318 // Skip non-existent authority.
2319 pop = null;
2320 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2321 Log.v(TAG_FILE, "No authority found for " + authorityId
2322 + ", skipping");
2323 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002324 }
Matthew Williamsba352712013-08-13 15:53:31 -07002325 } else if (parser.getDepth() == 2 &&
2326 pop != null &&
2327 "extra".equals(tagName)) {
2328 parseExtra(parser, pop.extras);
Matthew Williamsfa774182013-06-18 15:44:11 -07002329 }
Matthew Williamsba352712013-08-13 15:53:31 -07002330 } catch (NumberFormatException e) {
2331 Log.d(TAG, "Invalid data in xml file.", e);
Matthew Williamsfa774182013-06-18 15:44:11 -07002332 }
Matthew Williamsba352712013-08-13 15:53:31 -07002333 }
2334 eventType = parser.next();
2335 } while(eventType != XmlPullParser.END_DOCUMENT);
Matthew Williamsfa774182013-06-18 15:44:11 -07002336 } catch (java.io.IOException e) {
Matthew Williamsba352712013-08-13 15:53:31 -07002337 Log.w(TAG_FILE, "Error reading pending data.", e);
2338 } catch (XmlPullParserException e) {
2339 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2340 Log.w(TAG_FILE, "Error parsing pending ops xml.", e);
2341 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002342 } finally {
Matthew Williamsfa774182013-06-18 15:44:11 -07002343 if (fis != null) {
2344 try {
2345 fis.close();
2346 } catch (java.io.IOException e1) {}
2347 }
2348 }
2349 }
Matthew Williamsba352712013-08-13 15:53:31 -07002350
2351 private static final String XML_ATTR_AUTHORITYID = "authority_id";
2352 private static final String XML_ATTR_SOURCE = "source";
2353 private static final String XML_ATTR_EXPEDITED = "expedited";
2354 private static final String XML_ATTR_REASON = "reason";
2355 private static final String XML_ATTR_VERSION = "version";
2356
Matthew Williamsfa774182013-06-18 15:44:11 -07002357 /**
Matthew Williamsba352712013-08-13 15:53:31 -07002358 * Write all currently pending ops to the pending ops file.
Matthew Williamsfa774182013-06-18 15:44:11 -07002359 */
Matthew Williamsba352712013-08-13 15:53:31 -07002360 private void writePendingOperationsLocked() {
2361 final int N = mPendingOperations.size();
2362 FileOutputStream fos = null;
2363 try {
2364 if (N == 0) {
2365 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2366 Log.v(TAG_FILE, "Truncating " + mPendingFile.getBaseFile());
Matthew Williamsfa774182013-06-18 15:44:11 -07002367 }
Matthew Williamsba352712013-08-13 15:53:31 -07002368 mPendingFile.truncate();
2369 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002370 }
Matthew Williamsba352712013-08-13 15:53:31 -07002371 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2372 Log.v(TAG_FILE, "Writing new " + mPendingFile.getBaseFile());
2373 }
2374 fos = mPendingFile.startWrite();
2375 XmlSerializer out = new FastXmlSerializer();
2376 out.setOutput(fos, "utf-8");
2377
2378 for (int i = 0; i < N; i++) {
2379 PendingOperation pop = mPendingOperations.get(i);
2380 writePendingOperationLocked(pop, out);
2381 }
2382 out.endDocument();
2383 mPendingFile.finishWrite(fos);
2384 } catch (java.io.IOException e1) {
2385 Log.w(TAG, "Error writing pending operations", e1);
2386 if (fos != null) {
2387 mPendingFile.failWrite(fos);
2388 }
2389 }
2390 }
2391
2392 /** Write all currently pending ops to the pending ops file. */
2393 private void writePendingOperationLocked(PendingOperation pop, XmlSerializer out)
2394 throws IOException {
2395 // Pending operation.
2396 out.startTag(null, "op");
2397
2398 out.attribute(null, XML_ATTR_VERSION, Integer.toString(PENDING_OPERATION_VERSION));
2399 out.attribute(null, XML_ATTR_AUTHORITYID, Integer.toString(pop.authorityId));
2400 out.attribute(null, XML_ATTR_SOURCE, Integer.toString(pop.syncSource));
2401 out.attribute(null, XML_ATTR_EXPEDITED, Boolean.toString(pop.expedited));
2402 out.attribute(null, XML_ATTR_REASON, Integer.toString(pop.reason));
2403 extrasToXml(out, pop.extras);
2404
2405 out.endTag(null, "op");
2406 }
2407
2408 /**
2409 * Append the given operation to the pending ops file; if unable to,
2410 * write all pending ops.
2411 */
2412 private void appendPendingOperationLocked(PendingOperation op) {
2413 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2414 Log.v(TAG, "Appending to " + mPendingFile.getBaseFile());
2415 }
2416 FileOutputStream fos = null;
2417 try {
2418 fos = mPendingFile.openAppend();
2419 } catch (java.io.IOException e) {
2420 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2421 Log.v(TAG, "Failed append; writing full file");
2422 }
2423 writePendingOperationsLocked();
2424 return;
2425 }
2426
2427 try {
2428 XmlSerializer out = new FastXmlSerializer();
2429 out.setOutput(fos, "utf-8");
2430 writePendingOperationLocked(op, out);
2431 out.endDocument();
2432 mPendingFile.finishWrite(fos);
2433 } catch (java.io.IOException e1) {
2434 Log.w(TAG, "Error writing appending operation", e1);
2435 mPendingFile.failWrite(fos);
2436 } finally {
2437 try {
2438 fos.close();
2439 } catch (IOException e) {}
Dianne Hackborn231cc602009-04-27 17:10:36 -07002440 }
2441 }
Costin Manolache360e4542009-09-04 13:36:04 -07002442
Dianne Hackborn231cc602009-04-27 17:10:36 -07002443 static private byte[] flattenBundle(Bundle bundle) {
2444 byte[] flatData = null;
2445 Parcel parcel = Parcel.obtain();
2446 try {
2447 bundle.writeToParcel(parcel, 0);
2448 flatData = parcel.marshall();
2449 } finally {
2450 parcel.recycle();
2451 }
2452 return flatData;
2453 }
Costin Manolache360e4542009-09-04 13:36:04 -07002454
Dianne Hackborn231cc602009-04-27 17:10:36 -07002455 static private Bundle unflattenBundle(byte[] flatData) {
2456 Bundle bundle;
2457 Parcel parcel = Parcel.obtain();
2458 try {
2459 parcel.unmarshall(flatData, 0, flatData.length);
2460 parcel.setDataPosition(0);
2461 bundle = parcel.readBundle();
2462 } catch (RuntimeException e) {
2463 // A RuntimeException is thrown if we were unable to parse the parcel.
2464 // Create an empty parcel in this case.
2465 bundle = new Bundle();
2466 } finally {
2467 parcel.recycle();
2468 }
2469 return bundle;
2470 }
Costin Manolache360e4542009-09-04 13:36:04 -07002471
Matthew Williamsfa774182013-06-18 15:44:11 -07002472 private void extrasToXml(XmlSerializer out, Bundle extras) throws java.io.IOException {
2473 for (String key : extras.keySet()) {
2474 out.startTag(null, "extra");
2475 out.attribute(null, "name", key);
2476 final Object value = extras.get(key);
2477 if (value instanceof Long) {
2478 out.attribute(null, "type", "long");
2479 out.attribute(null, "value1", value.toString());
2480 } else if (value instanceof Integer) {
2481 out.attribute(null, "type", "integer");
2482 out.attribute(null, "value1", value.toString());
2483 } else if (value instanceof Boolean) {
2484 out.attribute(null, "type", "boolean");
2485 out.attribute(null, "value1", value.toString());
2486 } else if (value instanceof Float) {
2487 out.attribute(null, "type", "float");
2488 out.attribute(null, "value1", value.toString());
2489 } else if (value instanceof Double) {
2490 out.attribute(null, "type", "double");
2491 out.attribute(null, "value1", value.toString());
2492 } else if (value instanceof String) {
2493 out.attribute(null, "type", "string");
2494 out.attribute(null, "value1", value.toString());
2495 } else if (value instanceof Account) {
2496 out.attribute(null, "type", "account");
2497 out.attribute(null, "value1", ((Account)value).name);
2498 out.attribute(null, "value2", ((Account)value).type);
2499 }
2500 out.endTag(null, "extra");
2501 }
2502 }
2503
Alon Albert57286f92012-10-09 14:21:38 -07002504 private void requestSync(Account account, int userId, int reason, String authority,
2505 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002506 // If this is happening in the system process, then call the syncrequest listener
2507 // to make a request back to the SyncManager directly.
2508 // If this is probably a test instance, then call back through the ContentResolver
2509 // which will know which userId to apply based on the Binder id.
2510 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2511 && mSyncRequestListener != null) {
Alon Albert57286f92012-10-09 14:21:38 -07002512 mSyncRequestListener.onSyncRequest(account, userId, reason, authority, extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002513 } else {
2514 ContentResolver.requestSync(account, authority, extras);
2515 }
2516 }
2517
Dianne Hackborn231cc602009-04-27 17:10:36 -07002518 public static final int STATISTICS_FILE_END = 0;
2519 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2520 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002521
Dianne Hackborn231cc602009-04-27 17:10:36 -07002522 /**
2523 * Read all sync statistics back in to the initial engine state.
2524 */
2525 private void readStatisticsLocked() {
2526 try {
2527 byte[] data = mStatisticsFile.readFully();
2528 Parcel in = Parcel.obtain();
2529 in.unmarshall(data, 0, data.length);
2530 in.setDataPosition(0);
2531 int token;
2532 int index = 0;
2533 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2534 if (token == STATISTICS_FILE_ITEM
2535 || token == STATISTICS_FILE_ITEM_OLD) {
2536 int day = in.readInt();
2537 if (token == STATISTICS_FILE_ITEM_OLD) {
2538 day = day - 2009 + 14245; // Magic!
2539 }
2540 DayStats ds = new DayStats(day);
2541 ds.successCount = in.readInt();
2542 ds.successTime = in.readLong();
2543 ds.failureCount = in.readInt();
2544 ds.failureTime = in.readLong();
2545 if (index < mDayStats.length) {
2546 mDayStats[index] = ds;
2547 index++;
2548 }
2549 } else {
2550 // Ooops.
2551 Log.w(TAG, "Unknown stats token: " + token);
2552 break;
2553 }
2554 }
2555 } catch (java.io.IOException e) {
2556 Log.i(TAG, "No initial statistics");
2557 }
2558 }
Costin Manolache360e4542009-09-04 13:36:04 -07002559
Dianne Hackborn231cc602009-04-27 17:10:36 -07002560 /**
2561 * Write all sync statistics to the sync status file.
2562 */
2563 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002564 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
2565 Log.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
2566 }
Costin Manolache360e4542009-09-04 13:36:04 -07002567
Dianne Hackborn231cc602009-04-27 17:10:36 -07002568 // The file is being written, so we don't need to have a scheduled
2569 // write until the next change.
2570 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002571
Dianne Hackborn231cc602009-04-27 17:10:36 -07002572 FileOutputStream fos = null;
2573 try {
2574 fos = mStatisticsFile.startWrite();
2575 Parcel out = Parcel.obtain();
2576 final int N = mDayStats.length;
2577 for (int i=0; i<N; i++) {
2578 DayStats ds = mDayStats[i];
2579 if (ds == null) {
2580 break;
2581 }
2582 out.writeInt(STATISTICS_FILE_ITEM);
2583 out.writeInt(ds.day);
2584 out.writeInt(ds.successCount);
2585 out.writeLong(ds.successTime);
2586 out.writeInt(ds.failureCount);
2587 out.writeLong(ds.failureTime);
2588 }
2589 out.writeInt(STATISTICS_FILE_END);
2590 fos.write(out.marshall());
2591 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002592
Dianne Hackborn231cc602009-04-27 17:10:36 -07002593 mStatisticsFile.finishWrite(fos);
2594 } catch (java.io.IOException e1) {
2595 Log.w(TAG, "Error writing stats", e1);
2596 if (fos != null) {
2597 mStatisticsFile.failWrite(fos);
2598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 }
2600 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002601
2602 /**
2603 * Dump state of PendingOperations.
2604 */
2605 public void dumpPendingOperations(StringBuilder sb) {
2606 sb.append("Pending Ops: ").append(mPendingOperations.size()).append(" operation(s)\n");
2607 for (PendingOperation pop : mPendingOperations) {
2608 sb.append("(" + pop.account)
Matthew Williamsba352712013-08-13 15:53:31 -07002609 .append(", u" + pop.userId)
Matthew Williamsfa774182013-06-18 15:44:11 -07002610 .append(", " + pop.authority)
2611 .append(", " + pop.extras)
2612 .append(")\n");
2613 }
2614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615}