blob: 5e94a9fc7679764a733d4999bf2d1c033caae762 [file] [log] [blame]
San Mehat67bd2cd2010-01-12 12:18:49 -08001/*
2 * Copyright (C) 2007 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.server;
18
San Mehat67bd2cd2010-01-12 12:18:49 -080019import android.net.LocalSocket;
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070020import android.net.LocalSocketAddress;
Chia-chi Yehe5750a32011-08-03 14:42:11 -070021import android.os.Handler;
22import android.os.HandlerThread;
23import android.os.Message;
San Mehat67bd2cd2010-01-12 12:18:49 -080024import android.os.SystemClock;
Robert Greenwalt470fd722012-01-18 12:51:15 -080025import android.util.LocalLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080026import android.util.Slog;
San Mehat67bd2cd2010-01-12 12:18:49 -080027
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080028import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080029import com.google.android.collect.Lists;
30
Robert Greenwalt470fd722012-01-18 12:51:15 -080031import java.nio.charset.Charsets;
32import java.io.FileDescriptor;
San Mehat67bd2cd2010-01-12 12:18:49 -080033import java.io.IOException;
34import java.io.InputStream;
35import java.io.OutputStream;
Robert Greenwalt470fd722012-01-18 12:51:15 -080036import java.io.PrintWriter;
San Mehat67bd2cd2010-01-12 12:18:49 -080037import java.util.ArrayList;
Robert Greenwalt470007f2012-02-07 11:36:55 -080038import java.util.concurrent.atomic.AtomicInteger;
Robert Greenwaltef215992012-06-05 11:48:40 -070039import java.util.concurrent.ArrayBlockingQueue;
40import java.util.concurrent.BlockingQueue;
41import java.util.concurrent.TimeUnit;
Robert Greenwalt470007f2012-02-07 11:36:55 -080042import java.util.LinkedList;
San Mehat67bd2cd2010-01-12 12:18:49 -080043
44/**
Jeff Sharkey31c6e482011-11-18 17:09:01 -080045 * Generic connector class for interfacing with a native daemon which uses the
46 * {@code libsysutils} FrameworkListener protocol.
San Mehat67bd2cd2010-01-12 12:18:49 -080047 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070048final class NativeDaemonConnector implements Runnable, Handler.Callback, Watchdog.Monitor {
Jeff Sharkey31c6e482011-11-18 17:09:01 -080049 private static final boolean LOGD = false;
San Mehat67bd2cd2010-01-12 12:18:49 -080050
Jeff Sharkey31c6e482011-11-18 17:09:01 -080051 private final String TAG;
52
53 private String mSocket;
54 private OutputStream mOutputStream;
Robert Greenwalt470fd722012-01-18 12:51:15 -080055 private LocalLog mLocalLog;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080056
Robert Greenwalt470007f2012-02-07 11:36:55 -080057 private final ResponseQueue mResponseQueue;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080058
San Mehat67bd2cd2010-01-12 12:18:49 -080059 private INativeDaemonConnectorCallbacks mCallbacks;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080060 private Handler mCallbackHandler;
San Mehat67bd2cd2010-01-12 12:18:49 -080061
Robert Greenwalt470007f2012-02-07 11:36:55 -080062 private AtomicInteger mSequenceNumber;
63
64 private static final int DEFAULT_TIMEOUT = 1 * 60 * 1000; /* 1 minute */
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070065 private static final long WARN_EXECUTE_DELAY_MS = 500; /* .5 sec */
Robert Greenwalt470007f2012-02-07 11:36:55 -080066
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070067 /** Lock held whenever communicating with native daemon. */
Jeff Sharkey31c6e482011-11-18 17:09:01 -080068 private final Object mDaemonLock = new Object();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070069
Kenny Root961aa8c2010-03-22 18:02:45 -070070 private final int BUFFER_SIZE = 4096;
71
Jeff Sharkey31c6e482011-11-18 17:09:01 -080072 NativeDaemonConnector(INativeDaemonConnectorCallbacks callbacks, String socket,
Robert Greenwalt470fd722012-01-18 12:51:15 -080073 int responseQueueSize, String logTag, int maxLogSize) {
San Mehat67bd2cd2010-01-12 12:18:49 -080074 mCallbacks = callbacks;
San Mehat67bd2cd2010-01-12 12:18:49 -080075 mSocket = socket;
Robert Greenwalt470007f2012-02-07 11:36:55 -080076 mResponseQueue = new ResponseQueue(responseQueueSize);
77 mSequenceNumber = new AtomicInteger(0);
Jeff Sharkey31c6e482011-11-18 17:09:01 -080078 TAG = logTag != null ? logTag : "NativeDaemonConnector";
Robert Greenwalt470fd722012-01-18 12:51:15 -080079 mLocalLog = new LocalLog(maxLogSize);
San Mehat67bd2cd2010-01-12 12:18:49 -080080 }
81
Chia-chi Yehe5750a32011-08-03 14:42:11 -070082 @Override
San Mehat67bd2cd2010-01-12 12:18:49 -080083 public void run() {
Chia-chi Yehe5750a32011-08-03 14:42:11 -070084 HandlerThread thread = new HandlerThread(TAG + ".CallbackHandler");
85 thread.start();
86 mCallbackHandler = new Handler(thread.getLooper(), this);
San Mehat67bd2cd2010-01-12 12:18:49 -080087
88 while (true) {
89 try {
90 listenToSocket();
91 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -080092 loge("Error in NativeDaemonConnector: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -080093 SystemClock.sleep(5000);
San Mehat67bd2cd2010-01-12 12:18:49 -080094 }
95 }
96 }
97
Chia-chi Yehe5750a32011-08-03 14:42:11 -070098 @Override
99 public boolean handleMessage(Message msg) {
100 String event = (String) msg.obj;
101 try {
Robert Greenwalt2d34b4a2012-04-20 13:08:02 -0700102 if (!mCallbacks.onEvent(msg.what, event, NativeDaemonEvent.unescapeArgs(event))) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800103 log(String.format("Unhandled event '%s'", event));
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700104 }
105 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800106 loge("Error handling '" + event + "': " + e);
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700107 }
108 return true;
109 }
110
San Mehat4c27e0e2010-01-29 05:22:17 -0800111 private void listenToSocket() throws IOException {
Kenny Root961aa8c2010-03-22 18:02:45 -0700112 LocalSocket socket = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800113
114 try {
115 socket = new LocalSocket();
116 LocalSocketAddress address = new LocalSocketAddress(mSocket,
117 LocalSocketAddress.Namespace.RESERVED);
118
119 socket.connect(address);
San Mehat67bd2cd2010-01-12 12:18:49 -0800120
121 InputStream inputStream = socket.getInputStream();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800122 synchronized (mDaemonLock) {
123 mOutputStream = socket.getOutputStream();
124 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800125
anga030bc882011-02-01 14:10:25 +0100126 mCallbacks.onDaemonConnected();
127
Kenny Root961aa8c2010-03-22 18:02:45 -0700128 byte[] buffer = new byte[BUFFER_SIZE];
129 int start = 0;
San Mehat67bd2cd2010-01-12 12:18:49 -0800130
131 while (true) {
Kenny Root961aa8c2010-03-22 18:02:45 -0700132 int count = inputStream.read(buffer, start, BUFFER_SIZE - start);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800133 if (count < 0) {
134 loge("got " + count + " reading with start = " + start);
135 break;
136 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800137
Kenny Root12da9d72010-09-02 22:18:14 -0700138 // Add our starting point to the count and reset the start.
139 count += start;
140 start = 0;
141
San Mehat67bd2cd2010-01-12 12:18:49 -0800142 for (int i = 0; i < count; i++) {
143 if (buffer[i] == 0) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800144 final String rawEvent = new String(
145 buffer, start, i - start, Charsets.UTF_8);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800146 log("RCV <- {" + rawEvent + "}");
San Mehat67bd2cd2010-01-12 12:18:49 -0800147
San Mehat67bd2cd2010-01-12 12:18:49 -0800148 try {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800149 final NativeDaemonEvent event = NativeDaemonEvent.parseRawEvent(
150 rawEvent);
151 if (event.isClassUnsolicited()) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800152 // TODO: migrate to sending NativeDaemonEvent instances
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800153 mCallbackHandler.sendMessage(mCallbackHandler.obtainMessage(
154 event.getCode(), event.getRawEvent()));
Irfan Sheriff1cd94ef2011-01-16 14:31:55 -0800155 } else {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800156 mResponseQueue.add(event.getCmdNumber(), event);
San Mehat67bd2cd2010-01-12 12:18:49 -0800157 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800158 } catch (IllegalArgumentException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800159 log("Problem parsing message: " + rawEvent + " - " + e);
San Mehat67bd2cd2010-01-12 12:18:49 -0800160 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800161
San Mehat67bd2cd2010-01-12 12:18:49 -0800162 start = i + 1;
163 }
164 }
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800165 if (start == 0) {
166 final String rawEvent = new String(buffer, start, count, Charsets.UTF_8);
167 log("RCV incomplete <- {" + rawEvent + "}");
168 }
Kenny Root12da9d72010-09-02 22:18:14 -0700169
170 // We should end at the amount we read. If not, compact then
171 // buffer and read again.
Kenny Root961aa8c2010-03-22 18:02:45 -0700172 if (start != count) {
173 final int remaining = BUFFER_SIZE - start;
174 System.arraycopy(buffer, start, buffer, 0, remaining);
175 start = remaining;
176 } else {
177 start = 0;
178 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800179 }
180 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800181 loge("Communications error: " + ex);
San Mehat4c27e0e2010-01-29 05:22:17 -0800182 throw ex;
183 } finally {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700184 synchronized (mDaemonLock) {
San Mehat4c27e0e2010-01-29 05:22:17 -0800185 if (mOutputStream != null) {
186 try {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800187 loge("closing stream for " + mSocket);
San Mehat4c27e0e2010-01-29 05:22:17 -0800188 mOutputStream.close();
189 } catch (IOException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800190 loge("Failed closing output stream: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -0800191 }
192 mOutputStream = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800193 }
San Mehat4c27e0e2010-01-29 05:22:17 -0800194 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800195
San Mehat4c27e0e2010-01-29 05:22:17 -0800196 try {
197 if (socket != null) {
198 socket.close();
199 }
200 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800201 loge("Failed closing socket: " + ex);
San Mehat67bd2cd2010-01-12 12:18:49 -0800202 }
203 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800204 }
205
San Mehat67bd2cd2010-01-12 12:18:49 -0800206 /**
Robert Greenwalt470007f2012-02-07 11:36:55 -0800207 * Make command for daemon, escaping arguments as needed.
San Mehat67bd2cd2010-01-12 12:18:49 -0800208 */
Robert Greenwaltd1925982012-03-12 15:37:40 -0700209 private void makeCommand(StringBuilder builder, String cmd, Object... args)
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700210 throws NativeDaemonConnectorException {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800211 // TODO: eventually enforce that cmd doesn't contain arguments
212 if (cmd.indexOf('\0') >= 0) {
213 throw new IllegalArgumentException("unexpected command: " + cmd);
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700214 }
215
Robert Greenwaltd1925982012-03-12 15:37:40 -0700216 builder.append(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800217 for (Object arg : args) {
218 final String argString = String.valueOf(arg);
219 if (argString.indexOf('\0') >= 0) {
220 throw new IllegalArgumentException("unexpected argument: " + arg);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700221 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800222
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800223 builder.append(' ');
224 appendEscaped(builder, argString);
225 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800226 }
San Mehatdeba6932010-01-20 15:14:31 -0800227
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700228 /**
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800229 * Issue the given command to the native daemon and return a single expected
230 * response.
231 *
232 * @throws NativeDaemonConnectorException when problem communicating with
233 * native daemon, or if the response matches
234 * {@link NativeDaemonEvent#isClassClientError()} or
235 * {@link NativeDaemonEvent#isClassServerError()}.
San Mehatdeba6932010-01-20 15:14:31 -0800236 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800237 public NativeDaemonEvent execute(Command cmd) throws NativeDaemonConnectorException {
238 return execute(cmd.mCmd, cmd.mArguments.toArray());
239 }
240
241 /**
242 * Issue the given command to the native daemon and return a single expected
243 * response.
244 *
245 * @throws NativeDaemonConnectorException when problem communicating with
246 * native daemon, or if the response matches
247 * {@link NativeDaemonEvent#isClassClientError()} or
248 * {@link NativeDaemonEvent#isClassServerError()}.
249 */
250 public NativeDaemonEvent execute(String cmd, Object... args)
251 throws NativeDaemonConnectorException {
252 final NativeDaemonEvent[] events = executeForList(cmd, args);
253 if (events.length != 1) {
254 throw new NativeDaemonConnectorException(
255 "Expected exactly one response, but received " + events.length);
256 }
257 return events[0];
258 }
259
260 /**
261 * Issue the given command to the native daemon and return any
262 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
263 * final terminal response.
264 *
265 * @throws NativeDaemonConnectorException when problem communicating with
266 * native daemon, or if the response matches
267 * {@link NativeDaemonEvent#isClassClientError()} or
268 * {@link NativeDaemonEvent#isClassServerError()}.
269 */
270 public NativeDaemonEvent[] executeForList(Command cmd) throws NativeDaemonConnectorException {
271 return executeForList(cmd.mCmd, cmd.mArguments.toArray());
272 }
273
274 /**
275 * Issue the given command to the native daemon and return any
276 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
277 * final terminal response.
278 *
279 * @throws NativeDaemonConnectorException when problem communicating with
280 * native daemon, or if the response matches
281 * {@link NativeDaemonEvent#isClassClientError()} or
282 * {@link NativeDaemonEvent#isClassServerError()}.
283 */
284 public NativeDaemonEvent[] executeForList(String cmd, Object... args)
San Mehat4c27e0e2010-01-29 05:22:17 -0800285 throws NativeDaemonConnectorException {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800286 return execute(DEFAULT_TIMEOUT, cmd, args);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800287 }
San Mehatdeba6932010-01-20 15:14:31 -0800288
Robert Greenwalt470007f2012-02-07 11:36:55 -0800289 /**
290 * Issue the given command to the native daemon and return any
291 * {@linke NativeDaemonEvent@isClassContinue()} responses, including the
292 * final terminal response. Note that the timeout does not count time in
293 * deep sleep.
294 *
295 * @throws NativeDaemonConnectorException when problem communicating with
296 * native daemon, or if the response matches
297 * {@link NativeDaemonEvent#isClassClientError()} or
298 * {@link NativeDaemonEvent#isClassServerError()}.
299 */
300 public NativeDaemonEvent[] execute(int timeout, String cmd, Object... args)
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800301 throws NativeDaemonConnectorException {
302 final ArrayList<NativeDaemonEvent> events = Lists.newArrayList();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700303
304 final int sequenceNumber = mSequenceNumber.incrementAndGet();
305 final StringBuilder cmdBuilder =
306 new StringBuilder(Integer.toString(sequenceNumber)).append(' ');
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700307 final long startTime = SystemClock.elapsedRealtime();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700308
309 makeCommand(cmdBuilder, cmd, args);
310
311 final String logCmd = cmdBuilder.toString(); /* includes cmdNum, cmd, args */
312 log("SND -> {" + logCmd + "}");
313
314 cmdBuilder.append('\0');
315 final String sentCmd = cmdBuilder.toString(); /* logCmd + \0 */
316
317 synchronized (mDaemonLock) {
318 if (mOutputStream == null) {
319 throw new NativeDaemonConnectorException("missing output stream");
320 } else {
321 try {
322 mOutputStream.write(sentCmd.getBytes(Charsets.UTF_8));
323 } catch (IOException e) {
324 throw new NativeDaemonConnectorException("problem sending command", e);
325 }
326 }
327 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800328
329 NativeDaemonEvent event = null;
330 do {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700331 event = mResponseQueue.remove(sequenceNumber, timeout, sentCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800332 if (event == null) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700333 loge("timed-out waiting for response to " + logCmd);
334 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800335 }
Robert Greenwaltb5aff3f2012-05-15 17:26:57 -0700336 log("RMV <- {" + event + "}");
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800337 events.add(event);
338 } while (event.isClassContinue());
339
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700340 final long endTime = SystemClock.elapsedRealtime();
341 if (endTime - startTime > WARN_EXECUTE_DELAY_MS) {
342 loge("NDC Command {" + logCmd + "} took too long (" + (endTime - startTime) + "ms)");
343 }
344
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800345 if (event.isClassClientError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700346 throw new NativeDaemonArgumentException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800347 }
348 if (event.isClassServerError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700349 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800350 }
351
352 return events.toArray(new NativeDaemonEvent[events.size()]);
353 }
354
355 /**
356 * Issue a command to the native daemon and return the raw responses.
357 *
358 * @deprecated callers should move to {@link #execute(String, Object...)}
359 * which returns parsed {@link NativeDaemonEvent}.
360 */
361 @Deprecated
362 public ArrayList<String> doCommand(String cmd) throws NativeDaemonConnectorException {
363 final ArrayList<String> rawEvents = Lists.newArrayList();
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800364 final NativeDaemonEvent[] events = executeForList(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800365 for (NativeDaemonEvent event : events) {
366 rawEvents.add(event.getRawEvent());
367 }
368 return rawEvents;
369 }
370
371 /**
372 * Issues a list command and returns the cooked list of all
373 * {@link NativeDaemonEvent#getMessage()} which match requested code.
374 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800375 @Deprecated
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800376 public String[] doListCommand(String cmd, int expectedCode)
377 throws NativeDaemonConnectorException {
378 final ArrayList<String> list = Lists.newArrayList();
379
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800380 final NativeDaemonEvent[] events = executeForList(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800381 for (int i = 0; i < events.length - 1; i++) {
382 final NativeDaemonEvent event = events[i];
383 final int code = event.getCode();
384 if (code == expectedCode) {
385 list.add(event.getMessage());
386 } else {
San Mehat4c27e0e2010-01-29 05:22:17 -0800387 throw new NativeDaemonConnectorException(
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800388 "unexpected list response " + code + " instead of " + expectedCode);
San Mehatdeba6932010-01-20 15:14:31 -0800389 }
390 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800391
392 final NativeDaemonEvent finalEvent = events[events.length - 1];
393 if (!finalEvent.isClassOk()) {
394 throw new NativeDaemonConnectorException("unexpected final event: " + finalEvent);
395 }
396
397 return list.toArray(new String[list.size()]);
398 }
399
400 /**
401 * Append the given argument to {@link StringBuilder}, escaping as needed,
402 * and surrounding with quotes when it contains spaces.
403 */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800404 @VisibleForTesting
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800405 static void appendEscaped(StringBuilder builder, String arg) {
406 final boolean hasSpaces = arg.indexOf(' ') >= 0;
407 if (hasSpaces) {
408 builder.append('"');
409 }
410
411 final int length = arg.length();
412 for (int i = 0; i < length; i++) {
413 final char c = arg.charAt(i);
414
415 if (c == '"') {
416 builder.append("\\\"");
417 } else if (c == '\\') {
418 builder.append("\\\\");
419 } else {
420 builder.append(c);
421 }
422 }
423
424 if (hasSpaces) {
425 builder.append('"');
426 }
427 }
428
429 private static class NativeDaemonArgumentException extends NativeDaemonConnectorException {
430 public NativeDaemonArgumentException(String command, NativeDaemonEvent event) {
431 super(command, event);
432 }
433
434 @Override
435 public IllegalArgumentException rethrowAsParcelableException() {
436 throw new IllegalArgumentException(getMessage(), this);
437 }
438 }
439
440 private static class NativeDaemonFailureException extends NativeDaemonConnectorException {
441 public NativeDaemonFailureException(String command, NativeDaemonEvent event) {
442 super(command, event);
443 }
San Mehatdeba6932010-01-20 15:14:31 -0800444 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700445
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800446 /**
447 * Command builder that handles argument list building.
448 */
449 public static class Command {
450 private String mCmd;
451 private ArrayList<Object> mArguments = Lists.newArrayList();
452
453 public Command(String cmd, Object... args) {
454 mCmd = cmd;
455 for (Object arg : args) {
456 appendArg(arg);
457 }
458 }
459
460 public Command appendArg(Object arg) {
461 mArguments.add(arg);
462 return this;
463 }
464 }
465
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700466 /** {@inheritDoc} */
467 public void monitor() {
468 synchronized (mDaemonLock) { }
469 }
Robert Greenwalt470fd722012-01-18 12:51:15 -0800470
471 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
472 mLocalLog.dump(fd, pw, args);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800473 pw.println();
474 mResponseQueue.dump(fd, pw, args);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800475 }
476
477 private void log(String logstring) {
478 if (LOGD) Slog.d(TAG, logstring);
479 mLocalLog.log(logstring);
480 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800481
482 private void loge(String logstring) {
483 Slog.e(TAG, logstring);
484 mLocalLog.log(logstring);
485 }
486
487 private static class ResponseQueue {
488
Robert Greenwaltef215992012-06-05 11:48:40 -0700489 private static class PendingCmd {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800490 public int cmdNum;
Robert Greenwaltef215992012-06-05 11:48:40 -0700491 public BlockingQueue<NativeDaemonEvent> responses =
492 new ArrayBlockingQueue<NativeDaemonEvent>(10);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800493 public String request;
Robert Greenwaltef215992012-06-05 11:48:40 -0700494
495 // The availableResponseCount member is used to track when we can remove this
496 // instance from the ResponseQueue.
497 // This is used under the protection of a sync of the mPendingCmds object.
498 // A positive value means we've had more writers retreive this object while
499 // a negative value means we've had more readers. When we've had an equal number
500 // (it goes to zero) we can remove this object from the mPendingCmds list.
501 // Note that we may have more responses for this command (and more readers
502 // coming), but that would result in a new PendingCmd instance being created
503 // and added with the same cmdNum.
504 // Also note that when this goes to zero it just means a parity of readers and
505 // writers have retrieved this object - not that they are done using it. The
506 // responses queue may well have more responses yet to be read or may get more
507 // responses added to it. But all those readers/writers have retreived and
508 // hold references to this instance already so it can be removed from
509 // mPendingCmds queue.
510 public int availableResponseCount;
511 public PendingCmd(int c, String r) {cmdNum = c; request = r;}
Robert Greenwalt470007f2012-02-07 11:36:55 -0800512 }
513
Robert Greenwaltef215992012-06-05 11:48:40 -0700514 private final LinkedList<PendingCmd> mPendingCmds;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800515 private int mMaxCount;
516
517 ResponseQueue(int maxCount) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700518 mPendingCmds = new LinkedList<PendingCmd>();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800519 mMaxCount = maxCount;
520 }
521
522 public void add(int cmdNum, NativeDaemonEvent response) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700523 PendingCmd found = null;
524 synchronized (mPendingCmds) {
525 for (PendingCmd pendingCmd : mPendingCmds) {
526 if (pendingCmd.cmdNum == cmdNum) {
527 found = pendingCmd;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800528 break;
529 }
530 }
531 if (found == null) {
532 // didn't find it - make sure our queue isn't too big before adding
Robert Greenwaltef215992012-06-05 11:48:40 -0700533 while (mPendingCmds.size() >= mMaxCount) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800534 Slog.e("NativeDaemonConnector.ResponseQueue",
Robert Greenwaltef215992012-06-05 11:48:40 -0700535 "more buffered than allowed: " + mPendingCmds.size() +
Robert Greenwalt470007f2012-02-07 11:36:55 -0800536 " >= " + mMaxCount);
537 // let any waiter timeout waiting for this
Robert Greenwaltef215992012-06-05 11:48:40 -0700538 PendingCmd pendingCmd = mPendingCmds.remove();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800539 Slog.e("NativeDaemonConnector.ResponseQueue",
Robert Greenwaltef215992012-06-05 11:48:40 -0700540 "Removing request: " + pendingCmd.request + " (" +
541 pendingCmd.cmdNum + ")");
Robert Greenwalt470007f2012-02-07 11:36:55 -0800542 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700543 found = new PendingCmd(cmdNum, null);
544 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800545 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700546 found.availableResponseCount++;
547 // if a matching remove call has already retrieved this we can remove this
548 // instance from our list
549 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800550 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700551 try {
552 found.responses.put(response);
553 } catch (InterruptedException e) { }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800554 }
555
556 // note that the timeout does not count time in deep sleep. If you don't want
557 // the device to sleep, hold a wakelock
558 public NativeDaemonEvent remove(int cmdNum, int timeoutMs, String origCmd) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700559 PendingCmd found = null;
560 synchronized (mPendingCmds) {
561 for (PendingCmd pendingCmd : mPendingCmds) {
562 if (pendingCmd.cmdNum == cmdNum) {
563 found = pendingCmd;
564 break;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800565 }
566 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700567 if (found == null) {
568 found = new PendingCmd(cmdNum, origCmd);
569 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800570 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700571 found.availableResponseCount--;
572 // if a matching add call has already retrieved this we can remove this
573 // instance from our list
574 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800575 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700576 NativeDaemonEvent result = null;
577 try {
578 result = found.responses.poll(timeoutMs, TimeUnit.MILLISECONDS);
579 } catch (InterruptedException e) {}
580 if (result == null) {
581 Slog.e("NativeDaemonConnector.ResponseQueue", "Timeout waiting for response");
582 }
583 return result;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800584 }
585
586 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
587 pw.println("Pending requests:");
Robert Greenwaltef215992012-06-05 11:48:40 -0700588 synchronized (mPendingCmds) {
589 for (PendingCmd pendingCmd : mPendingCmds) {
590 pw.println(" Cmd " + pendingCmd.cmdNum + " - " + pendingCmd.request);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800591 }
592 }
593 }
594 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800595}