RetryManager.java revision 22d85a8e3a575a6d01d2c788587971657dfe20c6
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.internal.telephony;
18
19import android.telephony.Rlog;
20import android.util.Pair;
21import android.text.TextUtils;
22
23import java.util.Random;
24import java.util.ArrayList;
25
26/**
27 * Retry manager allows a simple way to declare a series of
28 * retry timeouts. After creating a RetryManager the configure
29 * method is used to define the sequence. A simple linear series
30 * may be initialized using configure with three integer parameters
31 * The other configure method allows a series to be declared using
32 * a string.
33 *<p>
34 * The format of the configuration string is a series of parameters
35 * separated by a comma. There are two name value pair parameters plus a series
36 * of delay times. The units of of these delay times is unspecified.
37 * The name value pairs which may be specified are:
38 *<ul>
39 *<li>max_retries=<value>
40 *<li>default_randomizationTime=<value>
41 *</ul>
42 *<p>
43 * max_retries is the number of times that incrementRetryCount
44 * maybe called before isRetryNeeded will return false. if value
45 * is infinite then isRetryNeeded will always return true.
46 *
47 * default_randomizationTime will be used as the randomizationTime
48 * for delay times which have no supplied randomizationTime. If
49 * default_randomizationTime is not defined it defaults to 0.
50 *<p>
51 * The other parameters define The series of delay times and each
52 * may have an optional randomization value separated from the
53 * delay time by a colon.
54 *<p>
55 * Examples:
56 * <ul>
57 * <li>3 retries with no randomization value which means its 0:
58 * <ul><li><code>"1000, 2000, 3000"</code></ul>
59 *
60 * <li>10 retries with a 500 default randomization value for each and
61 * the 4..10 retries all using 3000 as the delay:
62 * <ul><li><code>"max_retries=10, default_randomization=500, 1000, 2000, 3000"</code></ul>
63 *
64 * <li>4 retries with a 100 as the default randomization value for the first 2 values and
65 * the other two having specified values of 500:
66 * <ul><li><code>"default_randomization=100, 1000, 2000, 4000:500, 5000:500"</code></ul>
67 *
68 * <li>Infinite number of retries with the first one at 1000, the second at 2000 all
69 * others will be at 3000.
70 * <ul><li><code>"max_retries=infinite,1000,2000,3000</code></ul>
71 * </ul>
72 *
73 * {@hide}
74 */
75public class RetryManager {
76    static public final String LOG_TAG = "RetryManager";
77    static public final boolean DBG = true;
78    static public final boolean VDBG = false;
79
80    /**
81     * Retry record with times in milli-seconds
82     */
83    private static class RetryRec {
84        RetryRec(int delayTime, int randomizationTime) {
85            mDelayTime = delayTime;
86            mRandomizationTime = randomizationTime;
87        }
88
89        int mDelayTime;
90        int mRandomizationTime;
91    }
92
93    /** The array of retry records */
94    private ArrayList<RetryRec> mRetryArray = new ArrayList<RetryRec>();
95
96    /** When true isRetryNeeded() will always return true */
97    private boolean mRetryForever;
98
99    /**
100     * The maximum number of retries to attempt before
101     * isRetryNeeded returns false
102     */
103    private int mMaxRetryCount;
104
105    /** The current number of retries */
106    private int mRetryCount;
107
108    /** Random number generator */
109    private Random mRng = new Random();
110
111    private String mConfig;
112
113    /** Constructor */
114    public RetryManager() {
115        if (VDBG) log("constructor");
116    }
117
118    @Override
119    public String toString() {
120        String ret = "RetryManager: forever=" + mRetryForever + ", maxRetry=" + mMaxRetryCount +
121                ", retry=" + mRetryCount + ",\n    " + mConfig;
122        for (RetryRec r : mRetryArray) {
123            ret += "\n    " + r.mDelayTime + ":" + r.mRandomizationTime;
124        }
125        return ret;
126    }
127
128    /**
129     * Configure for a simple linear sequence of times plus
130     * a random value.
131     *
132     * @param maxRetryCount is the maximum number of retries
133     *        before isRetryNeeded returns false.
134     * @param retryTime is a time that will be returned by getRetryTime.
135     * @param randomizationTime a random value between 0 and
136     *        randomizationTime will be added to retryTime. this
137     *        parameter may be 0.
138     * @return true if successful
139     */
140    public boolean configure(int maxRetryCount, int retryTime, int randomizationTime) {
141        Pair<Boolean, Integer> value;
142
143        if (VDBG) log("configure: " + maxRetryCount + ", " + retryTime + "," + randomizationTime);
144
145        if (!validateNonNegativeInt("maxRetryCount", maxRetryCount)) {
146            return false;
147        }
148
149        if (!validateNonNegativeInt("retryTime", retryTime)) {
150            return false;
151        }
152
153        if (!validateNonNegativeInt("randomizationTime", randomizationTime)) {
154            return false;
155        }
156
157        mMaxRetryCount = maxRetryCount;
158        resetRetryCount();
159        mRetryArray.clear();
160        mRetryArray.add(new RetryRec(retryTime, randomizationTime));
161
162        return true;
163    }
164
165    /**
166     * Configure for using string which allow arbitrary
167     * sequences of times. See class comments for the
168     * string format.
169     *
170     * @return true if successful
171     */
172    public boolean configure(String configStr) {
173        // Strip quotes if present.
174        if ((configStr.startsWith("\"") && configStr.endsWith("\""))) {
175            configStr = configStr.substring(1, configStr.length()-1);
176        }
177        if (VDBG) log("configure: '" + configStr + "'");
178        mConfig = configStr;
179
180        if (!TextUtils.isEmpty(configStr)) {
181            int defaultRandomization = 0;
182
183            if (VDBG) log("configure: not empty");
184
185            mMaxRetryCount = 0;
186            resetRetryCount();
187            mRetryArray.clear();
188
189            String strArray[] = configStr.split(",");
190            for (int i = 0; i < strArray.length; i++) {
191                if (VDBG) log("configure: strArray[" + i + "]='" + strArray[i] + "'");
192                Pair<Boolean, Integer> value;
193                String splitStr[] = strArray[i].split("=", 2);
194                splitStr[0] = splitStr[0].trim();
195                if (VDBG) log("configure: splitStr[0]='" + splitStr[0] + "'");
196                if (splitStr.length > 1) {
197                    splitStr[1] = splitStr[1].trim();
198                    if (VDBG) log("configure: splitStr[1]='" + splitStr[1] + "'");
199                    if (TextUtils.equals(splitStr[0], "default_randomization")) {
200                        value = parseNonNegativeInt(splitStr[0], splitStr[1]);
201                        if (!value.first) return false;
202                        defaultRandomization = value.second;
203                    } else if (TextUtils.equals(splitStr[0], "max_retries")) {
204                        if (TextUtils.equals("infinite",splitStr[1])) {
205                            mRetryForever = true;
206                        } else {
207                            value = parseNonNegativeInt(splitStr[0], splitStr[1]);
208                            if (!value.first) return false;
209                            mMaxRetryCount = value.second;
210                        }
211                    } else {
212                        Rlog.e(LOG_TAG, "Unrecognized configuration name value pair: "
213                                        + strArray[i]);
214                        return false;
215                    }
216                } else {
217                    /**
218                     * Assume a retry time with an optional randomization value
219                     * following a ":"
220                     */
221                    splitStr = strArray[i].split(":", 2);
222                    splitStr[0] = splitStr[0].trim();
223                    RetryRec rr = new RetryRec(0, 0);
224                    value = parseNonNegativeInt("delayTime", splitStr[0]);
225                    if (!value.first) return false;
226                    rr.mDelayTime = value.second;
227
228                    // Check if optional randomization value present
229                    if (splitStr.length > 1) {
230                        splitStr[1] = splitStr[1].trim();
231                        if (VDBG) log("configure: splitStr[1]='" + splitStr[1] + "'");
232                        value = parseNonNegativeInt("randomizationTime", splitStr[1]);
233                        if (!value.first) return false;
234                        rr.mRandomizationTime = value.second;
235                    } else {
236                        rr.mRandomizationTime = defaultRandomization;
237                    }
238                    mRetryArray.add(rr);
239                }
240            }
241            if (mRetryArray.size() > mMaxRetryCount) {
242                mMaxRetryCount = mRetryArray.size();
243                if (VDBG) log("configure: setting mMaxRetryCount=" + mMaxRetryCount);
244            }
245            if (VDBG) log("configure: true");
246            return true;
247        } else {
248            if (VDBG) log("configure: false it's empty");
249            return false;
250        }
251    }
252
253    /**
254     * Report whether data reconnection should be retried
255     *
256     * @return {@code true} if the max retries has not been reached. {@code
257     *         false} otherwise.
258     */
259    public boolean isRetryNeeded() {
260        boolean retVal = mRetryForever || (mRetryCount < mMaxRetryCount);
261        if (DBG) log("isRetryNeeded: " + retVal);
262        return retVal;
263    }
264
265    /**
266     * Return the timer that should be used to trigger the data reconnection
267     */
268    public int getRetryTimer() {
269        int index;
270        if (mRetryCount < mRetryArray.size()) {
271            index = mRetryCount;
272        } else {
273            index = mRetryArray.size() - 1;
274        }
275
276        int retVal;
277        if ((index >= 0) && (index < mRetryArray.size())) {
278            retVal = mRetryArray.get(index).mDelayTime + nextRandomizationTime(index);
279        } else {
280            retVal = 0;
281        }
282
283        if (DBG) log("getRetryTimer: " + retVal);
284        return retVal;
285    }
286
287    /**
288     * @return retry count
289     */
290    public int getRetryCount() {
291        if (DBG) log("getRetryCount: " + mRetryCount);
292        return mRetryCount;
293    }
294
295    /**
296     * Increase the retry counter, does not change retry forever.
297     */
298    public void increaseRetryCount() {
299        mRetryCount++;
300        if (mRetryCount > mMaxRetryCount) {
301            mRetryCount = mMaxRetryCount;
302        }
303        if (DBG) log("increaseRetryCount: " + mRetryCount);
304    }
305
306    /**
307     * Set retry count to the specified value
308     */
309    public void setRetryCount(int count) {
310        mRetryCount = count;
311        if (mRetryCount > mMaxRetryCount) {
312            mRetryCount = mMaxRetryCount;
313        }
314
315        if (mRetryCount < 0) {
316            mRetryCount = 0;
317        }
318
319        if (DBG) log("setRetryCount: " + mRetryCount);
320    }
321
322    /**
323     * Set retry forever to the specified value
324     */
325    public void setRetryForever(boolean retryForever) {
326        mRetryForever = retryForever;
327        if (DBG) log("setRetryForever: " + mRetryForever);
328    }
329
330    /**
331     * Clear the data-retry counter
332     */
333    public void resetRetryCount() {
334        mRetryCount = 0;
335        if (DBG) log("resetRetryCount: " + mRetryCount);
336    }
337
338    /**
339     * Retry forever using last timeout time.
340     */
341    public void retryForeverUsingLastTimeout() {
342        mRetryCount = mMaxRetryCount;
343        mRetryForever = true;
344        if (DBG) log("retryForeverUsingLastTimeout: " + mRetryForever + ", " + mRetryCount);
345    }
346
347    /**
348     * @return true if retrying forever
349     */
350    public boolean isRetryForever() {
351        if (DBG) log("isRetryForever: " + mRetryForever);
352        return mRetryForever;
353    }
354
355    /**
356     * Parse an integer validating the value is not negative.
357     *
358     * @param name
359     * @param stringValue
360     * @return Pair.first == true if stringValue an integer >= 0
361     */
362    private Pair<Boolean, Integer> parseNonNegativeInt(String name, String stringValue) {
363        int value;
364        Pair<Boolean, Integer> retVal;
365        try {
366            value = Integer.parseInt(stringValue);
367            retVal = new Pair<Boolean, Integer>(validateNonNegativeInt(name, value), value);
368        } catch (NumberFormatException e) {
369            Rlog.e(LOG_TAG, name + " bad value: " + stringValue, e);
370            retVal = new Pair<Boolean, Integer>(false, 0);
371        }
372        if (VDBG) log("parseNonNetativeInt: " + name + ", " + stringValue + ", "
373                    + retVal.first + ", " + retVal.second);
374        return retVal;
375    }
376
377    /**
378     * Validate an integer is >= 0 and logs an error if not
379     *
380     * @param name
381     * @param value
382     * @return Pair.first
383     */
384    private boolean validateNonNegativeInt(String name, int value) {
385        boolean retVal;
386        if (value < 0) {
387            Rlog.e(LOG_TAG, name + " bad value: is < 0");
388            retVal = false;
389        } else {
390            retVal = true;
391        }
392        if (VDBG) log("validateNonNegative: " + name + ", " + value + ", " + retVal);
393        return retVal;
394    }
395
396    /**
397     * Return next random number for the index
398     */
399    private int nextRandomizationTime(int index) {
400        int randomTime = mRetryArray.get(index).mRandomizationTime;
401        if (randomTime == 0) {
402            return 0;
403        } else {
404            return mRng.nextInt(randomTime);
405        }
406    }
407
408    private void log(String s) {
409        Rlog.d(LOG_TAG, "[RM] " + s);
410    }
411}
412