1/*
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
17package com.android.common;
18
19import android.content.SharedPreferences;
20import android.net.http.AndroidHttpClient;
21import android.text.format.Time;
22
23import java.util.Map;
24import java.util.TreeSet;
25
26/**
27 * Tracks the success/failure history of a particular network operation in
28 * persistent storage and computes retry strategy accordingly.  Handles
29 * exponential backoff, periodic rescheduling, event-driven triggering,
30 * retry-after moratorium intervals, etc. based on caller-specified parameters.
31 *
32 * <p>This class does not directly perform or invoke any operations,
33 * it only keeps track of the schedule.  Somebody else needs to call
34 * {@link #getNextTimeMillis()} as appropriate and do the actual work.
35 */
36public class OperationScheduler {
37    /** Tunable parameter options for {@link #getNextTimeMillis}. */
38    public static class Options {
39        /** Wait this long after every error before retrying. */
40        public long backoffFixedMillis = 0;
41
42        /** Wait this long times the number of consecutive errors so far before retrying. */
43        public long backoffIncrementalMillis = 5000;
44
45        /** Maximum duration of moratorium to honor.  Mostly an issue for clock rollbacks. */
46        public long maxMoratoriumMillis = 24 * 3600 * 1000;
47
48        /** Minimum duration after success to wait before allowing another trigger. */
49        public long minTriggerMillis = 0;
50
51        /** Automatically trigger this long after the last success. */
52        public long periodicIntervalMillis = 0;
53
54        @Override
55        public String toString() {
56            return String.format(
57                    "OperationScheduler.Options[backoff=%.1f+%.1f max=%.1f min=%.1f period=%.1f]",
58                    backoffFixedMillis / 1000.0, backoffIncrementalMillis / 1000.0,
59                    maxMoratoriumMillis / 1000.0, minTriggerMillis / 1000.0,
60                    periodicIntervalMillis / 1000.0);
61        }
62    }
63
64    private static final String PREFIX = "OperationScheduler_";
65    private final SharedPreferences mStorage;
66
67    /**
68     * Initialize the scheduler state.
69     * @param storage to use for recording the state of operations across restarts/reboots
70     */
71    public OperationScheduler(SharedPreferences storage) {
72        mStorage = storage;
73    }
74
75    /**
76     * Parse scheduler options supplied in this string form:
77     *
78     * <pre>
79     * backoff=(fixed)+(incremental) max=(maxmoratorium) min=(mintrigger) [period=](interval)
80     * </pre>
81     *
82     * All values are times in (possibly fractional) <em>seconds</em> (not milliseconds).
83     * Omitted settings are left at whatever existing default value was passed in.
84     *
85     * <p>
86     * The default options: <code>backoff=0+5 max=86400 min=0 period=0</code><br>
87     * Fractions are OK: <code>backoff=+2.5 period=10.0</code><br>
88     * The "period=" can be omitted: <code>3600</code><br>
89     *
90     * @param spec describing some or all scheduler options.
91     * @param options to update with parsed values.
92     * @return the options passed in (for convenience)
93     * @throws IllegalArgumentException if the syntax is invalid
94     */
95    public static Options parseOptions(String spec, Options options)
96            throws IllegalArgumentException {
97        for (String param : spec.split(" +")) {
98            if (param.length() == 0) continue;
99            if (param.startsWith("backoff=")) {
100                int plus = param.indexOf('+', 8);
101                if (plus < 0) {
102                    options.backoffFixedMillis = parseSeconds(param.substring(8));
103                } else {
104                    if (plus > 8) {
105                        options.backoffFixedMillis = parseSeconds(param.substring(8, plus));
106                    }
107                    options.backoffIncrementalMillis = parseSeconds(param.substring(plus + 1));
108                }
109            } else if (param.startsWith("max=")) {
110                options.maxMoratoriumMillis = parseSeconds(param.substring(4));
111            } else if (param.startsWith("min=")) {
112                options.minTriggerMillis = parseSeconds(param.substring(4));
113            } else if (param.startsWith("period=")) {
114                options.periodicIntervalMillis = parseSeconds(param.substring(7));
115            } else {
116                options.periodicIntervalMillis = parseSeconds(param);
117            }
118        }
119        return options;
120    }
121
122    private static long parseSeconds(String param) throws NumberFormatException {
123        return (long) (Float.parseFloat(param) * 1000);
124    }
125
126    /**
127     * Compute the time of the next operation.  Does not modify any state
128     * (unless the clock rolls backwards, in which case timers are reset).
129     *
130     * @param options to use for this computation.
131     * @return the wall clock time ({@link System#currentTimeMillis()}) when the
132     * next operation should be attempted -- immediately, if the return value is
133     * before the current time.
134     */
135    public long getNextTimeMillis(Options options) {
136        boolean enabledState = mStorage.getBoolean(PREFIX + "enabledState", true);
137        if (!enabledState) return Long.MAX_VALUE;
138
139        boolean permanentError = mStorage.getBoolean(PREFIX + "permanentError", false);
140        if (permanentError) return Long.MAX_VALUE;
141
142        // We do quite a bit of limiting to prevent a clock rollback from totally
143        // hosing the scheduler.  Times which are supposed to be in the past are
144        // clipped to the current time so we don't languish forever.
145
146        int errorCount = mStorage.getInt(PREFIX + "errorCount", 0);
147        long now = currentTimeMillis();
148        long lastSuccessTimeMillis = getTimeBefore(PREFIX + "lastSuccessTimeMillis", now);
149        long lastErrorTimeMillis = getTimeBefore(PREFIX + "lastErrorTimeMillis", now);
150        long triggerTimeMillis = mStorage.getLong(PREFIX + "triggerTimeMillis", Long.MAX_VALUE);
151        long moratoriumSetMillis = getTimeBefore(PREFIX + "moratoriumSetTimeMillis", now);
152        long moratoriumTimeMillis = getTimeBefore(PREFIX + "moratoriumTimeMillis",
153                moratoriumSetMillis + options.maxMoratoriumMillis);
154
155        long time = triggerTimeMillis;
156        if (options.periodicIntervalMillis > 0) {
157            time = Math.min(time, lastSuccessTimeMillis + options.periodicIntervalMillis);
158        }
159
160        time = Math.max(time, moratoriumTimeMillis);
161        time = Math.max(time, lastSuccessTimeMillis + options.minTriggerMillis);
162        if (errorCount > 0) {
163            time = Math.max(time, lastErrorTimeMillis + options.backoffFixedMillis +
164                    options.backoffIncrementalMillis * errorCount);
165        }
166        return time;
167    }
168
169    /**
170     * Return the last time the operation completed.  Does not modify any state.
171     *
172     * @return the wall clock time when {@link #onSuccess()} was last called.
173     */
174    public long getLastSuccessTimeMillis() {
175        return mStorage.getLong(PREFIX + "lastSuccessTimeMillis", 0);
176    }
177
178    /**
179     * Return the last time the operation was attempted.  Does not modify any state.
180     *
181     * @return the wall clock time when {@link #onSuccess()} or {@link
182     * #onTransientError()} was last called.
183     */
184    public long getLastAttemptTimeMillis() {
185        return Math.max(
186                mStorage.getLong(PREFIX + "lastSuccessTimeMillis", 0),
187                mStorage.getLong(PREFIX + "lastErrorTimeMillis", 0));
188    }
189
190    /**
191     * Fetch a {@link SharedPreferences} property, but force it to be before
192     * a certain time, updating the value if necessary.  This is to recover
193     * gracefully from clock rollbacks which could otherwise strand our timers.
194     *
195     * @param name of SharedPreferences key
196     * @param max time to allow in result
197     * @return current value attached to key (default 0), limited by max
198     */
199    private long getTimeBefore(String name, long max) {
200        long time = mStorage.getLong(name, 0);
201        if (time > max) mStorage.edit().putLong(name, (time = max)).commit();
202        return time;
203    }
204
205    /**
206     * Request an operation to be performed at a certain time.  The actual
207     * scheduled time may be affected by error backoff logic and defined
208     * minimum intervals.  Use {@link Long#MAX_VALUE} to disable triggering.
209     *
210     * @param millis wall clock time ({@link System#currentTimeMillis()}) to
211     * trigger another operation; 0 to trigger immediately
212     */
213    public void setTriggerTimeMillis(long millis) {
214        mStorage.edit().putLong(PREFIX + "triggerTimeMillis", millis).commit();
215    }
216
217    /**
218     * Forbid any operations until after a certain (absolute) time.
219     * Limited by {@link #Options.maxMoratoriumMillis}.
220     *
221     * @param millis wall clock time ({@link System#currentTimeMillis()})
222     * when operations should be allowed again; 0 to remove moratorium
223     */
224    public void setMoratoriumTimeMillis(long millis) {
225        mStorage.edit()
226                .putLong(PREFIX + "moratoriumTimeMillis", millis)
227                .putLong(PREFIX + "moratoriumSetTimeMillis", currentTimeMillis())
228                .commit();
229    }
230
231    /**
232     * Forbid any operations until after a certain time, as specified in
233     * the format used by the HTTP "Retry-After" header.
234     * Limited by {@link #Options.maxMoratoriumMillis}.
235     *
236     * @param retryAfter moratorium time in HTTP format
237     * @return true if a time was successfully parsed
238     */
239    public boolean setMoratoriumTimeHttp(String retryAfter) {
240        try {
241            long ms = Long.valueOf(retryAfter) * 1000;
242            setMoratoriumTimeMillis(ms + currentTimeMillis());
243            return true;
244        } catch (NumberFormatException nfe) {
245            try {
246                setMoratoriumTimeMillis(AndroidHttpClient.parseDate(retryAfter));
247                return true;
248            } catch (IllegalArgumentException iae) {
249                return false;
250            }
251        }
252    }
253
254    /**
255     * Enable or disable all operations.  When disabled, all calls to
256     * {@link #getNextTimeMillis()} return {@link Long#MAX_VALUE}.
257     * Commonly used when data network availability goes up and down.
258     *
259     * @param enabled if operations can be performed
260     */
261    public void setEnabledState(boolean enabled) {
262        mStorage.edit().putBoolean(PREFIX + "enabledState", enabled).commit();
263    }
264
265    /**
266     * Report successful completion of an operation.  Resets all error
267     * counters, clears any trigger directives, and records the success.
268     */
269    public void onSuccess() {
270        resetTransientError();
271        resetPermanentError();
272        mStorage.edit()
273                .remove(PREFIX + "errorCount")
274                .remove(PREFIX + "lastErrorTimeMillis")
275                .remove(PREFIX + "permanentError")
276                .remove(PREFIX + "triggerTimeMillis")
277                .putLong(PREFIX + "lastSuccessTimeMillis", currentTimeMillis()).commit();
278    }
279
280    /**
281     * Report a transient error (usually a network failure).  Increments
282     * the error count and records the time of the latest error for backoff
283     * purposes.
284     */
285    public void onTransientError() {
286        mStorage.edit().putLong(PREFIX + "lastErrorTimeMillis", currentTimeMillis()).commit();
287        mStorage.edit().putInt(PREFIX + "errorCount",
288                mStorage.getInt(PREFIX + "errorCount", 0) + 1).commit();
289    }
290
291    /**
292     * Reset all transient error counts, allowing the next operation to proceed
293     * immediately without backoff.  Commonly used on network state changes, when
294     * partial progress occurs (some data received), and in other circumstances
295     * where there is reason to hope things might start working better.
296     */
297    public void resetTransientError() {
298        mStorage.edit().remove(PREFIX + "errorCount").commit();
299    }
300
301    /**
302     * Report a permanent error that will not go away until further notice.
303     * No operation will be scheduled until {@link #resetPermanentError()}
304     * is called.  Commonly used for authentication failures (which are reset
305     * when the accounts database is updated).
306     */
307    public void onPermanentError() {
308        mStorage.edit().putBoolean(PREFIX + "permanentError", true).commit();
309    }
310
311    /**
312     * Reset any permanent error status set by {@link #onPermanentError},
313     * allowing operations to be scheduled as normal.
314     */
315    public void resetPermanentError() {
316        mStorage.edit().remove(PREFIX + "permanentError").commit();
317    }
318
319    /**
320     * Return a string description of the scheduler state for debugging.
321     */
322    public String toString() {
323        StringBuilder out = new StringBuilder("[OperationScheduler:");
324        for (String key : new TreeSet<String>(mStorage.getAll().keySet())) {  // Sort keys
325            if (key.startsWith(PREFIX)) {
326                if (key.endsWith("TimeMillis")) {
327                    Time time = new Time();
328                    time.set(mStorage.getLong(key, 0));
329                    out.append(" ").append(key.substring(PREFIX.length(), key.length() - 10));
330                    out.append("=").append(time.format("%Y-%m-%d/%H:%M:%S"));
331                } else {
332                    out.append(" ").append(key.substring(PREFIX.length()));
333                    out.append("=").append(mStorage.getAll().get(key).toString());
334                }
335            }
336        }
337        return out.append("]").toString();
338    }
339
340    /**
341     * Gets the current time.  Can be overridden for unit testing.
342     *
343     * @return {@link System#currentTimeMillis()}
344     */
345    protected long currentTimeMillis() {
346        return System.currentTimeMillis();
347    }
348}
349