1/*
2 * Copyright (C) 2017 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 */
16package com.android.server.am;
17
18import android.annotation.NonNull;
19import android.content.ComponentName;
20import android.content.Context;
21import android.content.Intent;
22import android.content.ServiceConnection;
23import android.os.Handler;
24import android.os.IBinder;
25import android.os.SystemClock;
26import android.os.UserHandle;
27import android.util.Slog;
28import android.util.TimeUtils;
29
30import com.android.internal.annotations.GuardedBy;
31import com.android.internal.annotations.VisibleForTesting;
32
33import java.io.PrintWriter;
34
35/**
36 * Connects to a given service component on a given user.
37 *
38 * - Call {@link #bind()} to create a connection.
39 * - Call {@link #unbind()} to disconnect.  Make sure to disconnect when the user stops.
40 *
41 * Add onConnected/onDisconnected callbacks as needed.
42 *
43 * When the target process gets killed (by OOM-killer, etc), then the activity manager will
44 * re-connect the connection automatically, in which case onServiceDisconnected() gets called
45 * and then onServiceConnected().
46 *
47 * However sometimes the activity manager just "kills" the connection -- like when the target
48 * package gets updated or the target process crashes multiple times in a row, in which case
49 * onBindingDied() gets called.  This class handles this case by re-connecting in the time
50 * {@link #mRebindBackoffMs}.  If this happens again, this class increases the back-off time
51 * by {@link #mRebindBackoffIncrease} and retry.  The back-off time is capped at
52 * {@link #mRebindMaxBackoffMs}.
53 *
54 * The back-off time will never be reset until {@link #unbind()} and {@link #bind()} are called
55 * explicitly.
56 *
57 * NOTE: This class does *not* handle package-updates -- i.e. even if the binding dies due to
58 * the target package being updated, this class won't reconnect.  This is because this class doesn't
59 * know what to do when the service component has gone missing, for example.  If the user of this
60 * class wants to restore the connection, then it should call {@link #unbind()} and {@link #bind}
61 * explicitly.
62 */
63public abstract class PersistentConnection<T> {
64    private final Object mLock = new Object();
65
66    private final static boolean DEBUG = false;
67
68    private final String mTag;
69    private final Context mContext;
70    private final Handler mHandler;
71    private final int mUserId;
72    private final ComponentName mComponentName;
73
74    private long mNextBackoffMs;
75
76    private final long mRebindBackoffMs;
77    private final double mRebindBackoffIncrease;
78    private final long mRebindMaxBackoffMs;
79
80    private long mReconnectTime;
81
82    // TODO too many booleans... Should clean up.
83
84    @GuardedBy("mLock")
85    private boolean mBound;
86
87    /**
88     * Whether {@link #bind()} has been called and {@link #unbind()} hasn't been yet; meaning this
89     * is the expected bind state from the caller's point of view.
90     */
91    @GuardedBy("mLock")
92    private boolean mShouldBeBound;
93
94    @GuardedBy("mLock")
95    private boolean mRebindScheduled;
96
97    @GuardedBy("mLock")
98    private boolean mIsConnected;
99
100    @GuardedBy("mLock")
101    private T mService;
102
103    private final ServiceConnection mServiceConnection = new ServiceConnection() {
104        @Override
105        public void onServiceConnected(ComponentName name, IBinder service) {
106            synchronized (mLock) {
107                if (!mBound) {
108                    // Callback came in after PersistentConnection.unbind() was called.
109                    // We just ignore this.
110                    // (We've already called unbindService() already in unbind)
111                    Slog.w(mTag, "Connected: " + mComponentName.flattenToShortString()
112                            + " u" + mUserId + " but not bound, ignore.");
113                    return;
114                }
115                Slog.i(mTag, "Connected: " + mComponentName.flattenToShortString()
116                        + " u" + mUserId);
117
118                mIsConnected = true;
119                mService = asInterface(service);
120            }
121        }
122
123        @Override
124        public void onServiceDisconnected(ComponentName name) {
125            synchronized (mLock) {
126                Slog.i(mTag, "Disconnected: " + mComponentName.flattenToShortString()
127                        + " u" + mUserId);
128
129                cleanUpConnectionLocked();
130            }
131        }
132
133        @Override
134        public void onBindingDied(ComponentName name) {
135            // Activity manager gave up; we'll schedule a re-connect by ourselves.
136            synchronized (mLock) {
137                if (!mBound) {
138                    // Callback came in late?
139                    Slog.w(mTag, "Binding died: " + mComponentName.flattenToShortString()
140                            + " u" + mUserId + " but not bound, ignore.");
141                    return;
142                }
143
144                Slog.w(mTag, "Binding died: " + mComponentName.flattenToShortString()
145                        + " u" + mUserId);
146                scheduleRebindLocked();
147            }
148        }
149    };
150
151    private final Runnable mBindForBackoffRunnable = () -> bindForBackoff();
152
153    public PersistentConnection(@NonNull String tag, @NonNull Context context,
154            @NonNull Handler handler, int userId, @NonNull ComponentName componentName,
155            long rebindBackoffSeconds, double rebindBackoffIncrease, long rebindMaxBackoffSeconds) {
156        mTag = tag;
157        mContext = context;
158        mHandler = handler;
159        mUserId = userId;
160        mComponentName = componentName;
161
162        mRebindBackoffMs = rebindBackoffSeconds * 1000;
163        mRebindBackoffIncrease = rebindBackoffIncrease;
164        mRebindMaxBackoffMs = rebindMaxBackoffSeconds * 1000;
165
166        mNextBackoffMs = mRebindBackoffMs;
167    }
168
169    public final ComponentName getComponentName() {
170        return mComponentName;
171    }
172
173    /**
174     * @return whether {@link #bind()} has been called and {@link #unbind()} hasn't.
175     *
176     * Note when the AM gives up on connection, this class detects it and un-bind automatically,
177     * and schedule rebind, and {@link #isBound} returns false when it's waiting for a retry.
178     */
179    public final boolean isBound() {
180        synchronized (mLock) {
181            return mBound;
182        }
183    }
184
185    /**
186     * @return whether re-bind is scheduled after the AM gives up on a connection.
187     */
188    public final boolean isRebindScheduled() {
189        synchronized (mLock) {
190            return mRebindScheduled;
191        }
192    }
193
194    /**
195     * @return whether connected.
196     */
197    public final boolean isConnected() {
198        synchronized (mLock) {
199            return mIsConnected;
200        }
201    }
202
203    /**
204     * @return the service binder interface.
205     */
206    public final T getServiceBinder() {
207        synchronized (mLock) {
208            return mService;
209        }
210    }
211
212    /**
213     * Connects to the service.
214     */
215    public final void bind() {
216        synchronized (mLock) {
217            mShouldBeBound = true;
218
219            bindInnerLocked(/* resetBackoff= */ true);
220        }
221    }
222
223    public final void bindInnerLocked(boolean resetBackoff) {
224        unscheduleRebindLocked();
225
226        if (mBound) {
227            return;
228        }
229        mBound = true;
230
231        if (resetBackoff) {
232            // Note this is the only place we reset the backoff time.
233            mNextBackoffMs = mRebindBackoffMs;
234        }
235
236        final Intent service = new Intent().setComponent(mComponentName);
237
238        if (DEBUG) {
239            Slog.d(mTag, "Attempting to connect to " + mComponentName);
240        }
241
242        final boolean success = mContext.bindServiceAsUser(service, mServiceConnection,
243                Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
244                mHandler, UserHandle.of(mUserId));
245
246        if (!success) {
247            Slog.e(mTag, "Binding: " + service.getComponent() + " u" + mUserId
248                    + " failed.");
249        }
250    }
251
252    final void bindForBackoff() {
253        synchronized (mLock) {
254            if (!mShouldBeBound) {
255                // Race condition -- by the time we got here, unbind() has already been called.
256                return;
257            }
258
259            bindInnerLocked(/* resetBackoff= */ false);
260        }
261    }
262
263    private void cleanUpConnectionLocked() {
264        mIsConnected = false;
265        mService = null;
266    }
267
268    /**
269     * Disconnect from the service.
270     */
271    public final void unbind() {
272        synchronized (mLock) {
273            mShouldBeBound = false;
274
275            unbindLocked();
276        }
277    }
278
279    private final void unbindLocked() {
280        unscheduleRebindLocked();
281
282        if (!mBound) {
283            return;
284        }
285        Slog.i(mTag, "Stopping: " + mComponentName.flattenToShortString() + " u" + mUserId);
286        mBound = false;
287        mContext.unbindService(mServiceConnection);
288
289        cleanUpConnectionLocked();
290    }
291
292    void unscheduleRebindLocked() {
293        injectRemoveCallbacks(mBindForBackoffRunnable);
294        mRebindScheduled = false;
295    }
296
297    void scheduleRebindLocked() {
298        unbindLocked();
299
300        if (!mRebindScheduled) {
301            Slog.i(mTag, "Scheduling to reconnect in " + mNextBackoffMs + " ms (uptime)");
302
303            mReconnectTime = injectUptimeMillis() + mNextBackoffMs;
304
305            injectPostAtTime(mBindForBackoffRunnable, mReconnectTime);
306
307            mNextBackoffMs = Math.min(mRebindMaxBackoffMs,
308                    (long) (mNextBackoffMs * mRebindBackoffIncrease));
309
310            mRebindScheduled = true;
311        }
312    }
313
314    /** Must be implemented by a subclass to convert an {@link IBinder} to a stub. */
315    protected abstract T asInterface(IBinder binder);
316
317    public void dump(String prefix, PrintWriter pw) {
318        synchronized (mLock) {
319            pw.print(prefix);
320            pw.print(mComponentName.flattenToShortString());
321            pw.print(mBound ? "  [bound]" : "  [not bound]");
322            pw.print(mIsConnected ? "  [connected]" : "  [not connected]");
323            if (mRebindScheduled) {
324                pw.print("  reconnect in ");
325                TimeUtils.formatDuration((mReconnectTime - injectUptimeMillis()), pw);
326            }
327            pw.println();
328
329            pw.print(prefix);
330            pw.print("  Next backoff(sec): ");
331            pw.print(mNextBackoffMs / 1000);
332        }
333    }
334
335    @VisibleForTesting
336    void injectRemoveCallbacks(Runnable r) {
337        mHandler.removeCallbacks(r);
338    }
339
340    @VisibleForTesting
341    void injectPostAtTime(Runnable r, long uptimeMillis) {
342        mHandler.postAtTime(r, uptimeMillis);
343    }
344
345    @VisibleForTesting
346    long injectUptimeMillis() {
347        return SystemClock.uptimeMillis();
348    }
349
350    @VisibleForTesting
351    long getNextBackoffMsForTest() {
352        return mNextBackoffMs;
353    }
354
355    @VisibleForTesting
356    long getReconnectTimeForTest() {
357        return mReconnectTime;
358    }
359
360    @VisibleForTesting
361    ServiceConnection getServiceConnectionForTest() {
362        return mServiceConnection;
363    }
364
365    @VisibleForTesting
366    Runnable getBindForBackoffRunnableForTest() {
367        return mBindForBackoffRunnable;
368    }
369
370    @VisibleForTesting
371    boolean shouldBeBoundForTest() {
372        return mShouldBeBound;
373    }
374}
375