Home | History | Annotate | Download | only in content
      1 /*
      2  * Copyright (C) 2010 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 
     17 package com.android.server.content;
     18 
     19 import android.accounts.Account;
     20 import android.content.pm.PackageManager;
     21 import android.content.pm.RegisteredServicesCache;
     22 import android.content.SyncAdapterType;
     23 import android.content.SyncAdaptersCache;
     24 import android.content.pm.RegisteredServicesCache.ServiceInfo;
     25 import android.os.SystemClock;
     26 import android.text.format.DateUtils;
     27 import android.util.Log;
     28 import android.util.Pair;
     29 
     30 import com.google.android.collect.Maps;
     31 
     32 import java.util.ArrayList;
     33 import java.util.Collection;
     34 import java.util.HashMap;
     35 import java.util.Iterator;
     36 import java.util.Map;
     37 
     38 /**
     39  * Queue of pending sync operations. Not inherently thread safe, external
     40  * callers are responsible for locking.
     41  *
     42  * @hide
     43  */
     44 public class SyncQueue {
     45     private static final String TAG = "SyncManager";
     46     private final SyncStorageEngine mSyncStorageEngine;
     47     private final SyncAdaptersCache mSyncAdapters;
     48     private final PackageManager mPackageManager;
     49 
     50     // A Map of SyncOperations operationKey -> SyncOperation that is designed for
     51     // quick lookup of an enqueued SyncOperation.
     52     private final HashMap<String, SyncOperation> mOperationsMap = Maps.newHashMap();
     53 
     54     public SyncQueue(PackageManager packageManager, SyncStorageEngine syncStorageEngine,
     55             final SyncAdaptersCache syncAdapters) {
     56         mPackageManager = packageManager;
     57         mSyncStorageEngine = syncStorageEngine;
     58         mSyncAdapters = syncAdapters;
     59     }
     60 
     61     public void addPendingOperations(int userId) {
     62         for (SyncStorageEngine.PendingOperation op : mSyncStorageEngine.getPendingOperations()) {
     63             if (op.userId != userId) continue;
     64 
     65             final Pair<Long, Long> backoff = mSyncStorageEngine.getBackoff(
     66                     op.account, op.userId, op.authority);
     67             final ServiceInfo<SyncAdapterType> syncAdapterInfo = mSyncAdapters.getServiceInfo(
     68                     SyncAdapterType.newKey(op.authority, op.account.type), op.userId);
     69             if (syncAdapterInfo == null) {
     70                 Log.w(TAG, "Missing sync adapter info for authority " + op.authority + ", userId "
     71                         + op.userId);
     72                 continue;
     73             }
     74             SyncOperation syncOperation = new SyncOperation(
     75                     op.account, op.userId, op.reason, op.syncSource, op.authority, op.extras,
     76                     0 /* delay */, backoff != null ? backoff.first : 0,
     77                     mSyncStorageEngine.getDelayUntilTime(op.account, op.userId, op.authority),
     78                     syncAdapterInfo.type.allowParallelSyncs());
     79             syncOperation.expedited = op.expedited;
     80             syncOperation.pendingOperation = op;
     81             add(syncOperation, op);
     82         }
     83     }
     84 
     85     public boolean add(SyncOperation operation) {
     86         return add(operation, null /* this is not coming from the database */);
     87     }
     88 
     89     private boolean add(SyncOperation operation,
     90             SyncStorageEngine.PendingOperation pop) {
     91         // - if an operation with the same key exists and this one should run earlier,
     92         //   update the earliestRunTime of the existing to the new time
     93         // - if an operation with the same key exists and if this one should run
     94         //   later, ignore it
     95         // - if no operation exists then add the new one
     96         final String operationKey = operation.key;
     97         final SyncOperation existingOperation = mOperationsMap.get(operationKey);
     98 
     99         if (existingOperation != null) {
    100             boolean changed = false;
    101             if (existingOperation.expedited == operation.expedited) {
    102                 final long newRunTime =
    103                         Math.min(existingOperation.earliestRunTime, operation.earliestRunTime);
    104                 if (existingOperation.earliestRunTime != newRunTime) {
    105                     existingOperation.earliestRunTime = newRunTime;
    106                     changed = true;
    107                 }
    108             } else {
    109                 if (operation.expedited) {
    110                     existingOperation.expedited = true;
    111                     changed = true;
    112                 }
    113             }
    114             return changed;
    115         }
    116 
    117         operation.pendingOperation = pop;
    118         if (operation.pendingOperation == null) {
    119             pop = new SyncStorageEngine.PendingOperation(
    120                     operation.account, operation.userId, operation.reason, operation.syncSource,
    121                     operation.authority, operation.extras, operation.expedited);
    122             pop = mSyncStorageEngine.insertIntoPending(pop);
    123             if (pop == null) {
    124                 throw new IllegalStateException("error adding pending sync operation "
    125                         + operation);
    126             }
    127             operation.pendingOperation = pop;
    128         }
    129 
    130         mOperationsMap.put(operationKey, operation);
    131         return true;
    132     }
    133 
    134     public void removeUser(int userId) {
    135         ArrayList<SyncOperation> opsToRemove = new ArrayList<SyncOperation>();
    136         for (SyncOperation op : mOperationsMap.values()) {
    137             if (op.userId == userId) {
    138                 opsToRemove.add(op);
    139             }
    140         }
    141 
    142         for (SyncOperation op : opsToRemove) {
    143             remove(op);
    144         }
    145     }
    146 
    147     /**
    148      * Remove the specified operation if it is in the queue.
    149      * @param operation the operation to remove
    150      */
    151     public void remove(SyncOperation operation) {
    152         SyncOperation operationToRemove = mOperationsMap.remove(operation.key);
    153         if (operationToRemove == null) {
    154             return;
    155         }
    156         if (!mSyncStorageEngine.deleteFromPending(operationToRemove.pendingOperation)) {
    157             final String errorMessage = "unable to find pending row for " + operationToRemove;
    158             Log.e(TAG, errorMessage, new IllegalStateException(errorMessage));
    159         }
    160     }
    161 
    162     public void onBackoffChanged(Account account, int userId, String providerName, long backoff) {
    163         // for each op that matches the account and provider update its
    164         // backoff and effectiveStartTime
    165         for (SyncOperation op : mOperationsMap.values()) {
    166             if (op.account.equals(account) && op.authority.equals(providerName)
    167                     && op.userId == userId) {
    168                 op.backoff = backoff;
    169                 op.updateEffectiveRunTime();
    170             }
    171         }
    172     }
    173 
    174     public void onDelayUntilTimeChanged(Account account, String providerName, long delayUntil) {
    175         // for each op that matches the account and provider update its
    176         // delayUntilTime and effectiveStartTime
    177         for (SyncOperation op : mOperationsMap.values()) {
    178             if (op.account.equals(account) && op.authority.equals(providerName)) {
    179                 op.delayUntil = delayUntil;
    180                 op.updateEffectiveRunTime();
    181             }
    182         }
    183     }
    184 
    185     public void remove(Account account, int userId, String authority) {
    186         Iterator<Map.Entry<String, SyncOperation>> entries = mOperationsMap.entrySet().iterator();
    187         while (entries.hasNext()) {
    188             Map.Entry<String, SyncOperation> entry = entries.next();
    189             SyncOperation syncOperation = entry.getValue();
    190             if (account != null && !syncOperation.account.equals(account)) {
    191                 continue;
    192             }
    193             if (authority != null && !syncOperation.authority.equals(authority)) {
    194                 continue;
    195             }
    196             if (userId != syncOperation.userId) {
    197                 continue;
    198             }
    199             entries.remove();
    200             if (!mSyncStorageEngine.deleteFromPending(syncOperation.pendingOperation)) {
    201                 final String errorMessage = "unable to find pending row for " + syncOperation;
    202                 Log.e(TAG, errorMessage, new IllegalStateException(errorMessage));
    203             }
    204         }
    205     }
    206 
    207     public Collection<SyncOperation> getOperations() {
    208         return mOperationsMap.values();
    209     }
    210 
    211     public void dump(StringBuilder sb) {
    212         final long now = SystemClock.elapsedRealtime();
    213         sb.append("SyncQueue: ").append(mOperationsMap.size()).append(" operation(s)\n");
    214         for (SyncOperation operation : mOperationsMap.values()) {
    215             sb.append("  ");
    216             if (operation.effectiveRunTime <= now) {
    217                 sb.append("READY");
    218             } else {
    219                 sb.append(DateUtils.formatElapsedTime((operation.effectiveRunTime - now) / 1000));
    220             }
    221             sb.append(" - ");
    222             sb.append(operation.dump(mPackageManager, false)).append("\n");
    223         }
    224     }
    225 }
    226