blob: 6a6c585fe73c73ee56ae2d402d4dc8842eeb34d0 [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 Sharkey31c6e482011-11-18 17:09:01 -080028import com.google.android.collect.Lists;
29
Robert Greenwalt470fd722012-01-18 12:51:15 -080030import java.nio.charset.Charsets;
31import java.io.FileDescriptor;
San Mehat67bd2cd2010-01-12 12:18:49 -080032import java.io.IOException;
33import java.io.InputStream;
34import java.io.OutputStream;
Robert Greenwalt470fd722012-01-18 12:51:15 -080035import java.io.PrintWriter;
San Mehat67bd2cd2010-01-12 12:18:49 -080036import java.util.ArrayList;
Robert Greenwalt470007f2012-02-07 11:36:55 -080037import java.util.concurrent.atomic.AtomicInteger;
38import java.util.LinkedList;
San Mehat67bd2cd2010-01-12 12:18:49 -080039
40/**
Jeff Sharkey31c6e482011-11-18 17:09:01 -080041 * Generic connector class for interfacing with a native daemon which uses the
42 * {@code libsysutils} FrameworkListener protocol.
San Mehat67bd2cd2010-01-12 12:18:49 -080043 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070044final class NativeDaemonConnector implements Runnable, Handler.Callback, Watchdog.Monitor {
Jeff Sharkey31c6e482011-11-18 17:09:01 -080045 private static final boolean LOGD = false;
San Mehat67bd2cd2010-01-12 12:18:49 -080046
Jeff Sharkey31c6e482011-11-18 17:09:01 -080047 private final String TAG;
48
49 private String mSocket;
50 private OutputStream mOutputStream;
Robert Greenwalt470fd722012-01-18 12:51:15 -080051 private LocalLog mLocalLog;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080052
Robert Greenwalt470007f2012-02-07 11:36:55 -080053 private final ResponseQueue mResponseQueue;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080054
San Mehat67bd2cd2010-01-12 12:18:49 -080055 private INativeDaemonConnectorCallbacks mCallbacks;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080056 private Handler mCallbackHandler;
San Mehat67bd2cd2010-01-12 12:18:49 -080057
Robert Greenwalt470007f2012-02-07 11:36:55 -080058 private AtomicInteger mSequenceNumber;
59
60 private static final int DEFAULT_TIMEOUT = 1 * 60 * 1000; /* 1 minute */
61
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070062 /** Lock held whenever communicating with native daemon. */
Jeff Sharkey31c6e482011-11-18 17:09:01 -080063 private final Object mDaemonLock = new Object();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070064
Kenny Root961aa8c2010-03-22 18:02:45 -070065 private final int BUFFER_SIZE = 4096;
66
Jeff Sharkey31c6e482011-11-18 17:09:01 -080067 NativeDaemonConnector(INativeDaemonConnectorCallbacks callbacks, String socket,
Robert Greenwalt470fd722012-01-18 12:51:15 -080068 int responseQueueSize, String logTag, int maxLogSize) {
San Mehat67bd2cd2010-01-12 12:18:49 -080069 mCallbacks = callbacks;
San Mehat67bd2cd2010-01-12 12:18:49 -080070 mSocket = socket;
Robert Greenwalt470007f2012-02-07 11:36:55 -080071 mResponseQueue = new ResponseQueue(responseQueueSize);
72 mSequenceNumber = new AtomicInteger(0);
Jeff Sharkey31c6e482011-11-18 17:09:01 -080073 TAG = logTag != null ? logTag : "NativeDaemonConnector";
Robert Greenwalt470fd722012-01-18 12:51:15 -080074 mLocalLog = new LocalLog(maxLogSize);
San Mehat67bd2cd2010-01-12 12:18:49 -080075 }
76
Chia-chi Yehe5750a32011-08-03 14:42:11 -070077 @Override
San Mehat67bd2cd2010-01-12 12:18:49 -080078 public void run() {
Chia-chi Yehe5750a32011-08-03 14:42:11 -070079 HandlerThread thread = new HandlerThread(TAG + ".CallbackHandler");
80 thread.start();
81 mCallbackHandler = new Handler(thread.getLooper(), this);
San Mehat67bd2cd2010-01-12 12:18:49 -080082
83 while (true) {
84 try {
85 listenToSocket();
86 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -080087 loge("Error in NativeDaemonConnector: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -080088 SystemClock.sleep(5000);
San Mehat67bd2cd2010-01-12 12:18:49 -080089 }
90 }
91 }
92
Chia-chi Yehe5750a32011-08-03 14:42:11 -070093 @Override
94 public boolean handleMessage(Message msg) {
95 String event = (String) msg.obj;
96 try {
Robert Greenwalt2d34b4a2012-04-20 13:08:02 -070097 if (!mCallbacks.onEvent(msg.what, event, NativeDaemonEvent.unescapeArgs(event))) {
Robert Greenwalt470007f2012-02-07 11:36:55 -080098 log(String.format("Unhandled event '%s'", event));
Chia-chi Yehe5750a32011-08-03 14:42:11 -070099 }
100 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800101 loge("Error handling '" + event + "': " + e);
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700102 }
103 return true;
104 }
105
San Mehat4c27e0e2010-01-29 05:22:17 -0800106 private void listenToSocket() throws IOException {
Kenny Root961aa8c2010-03-22 18:02:45 -0700107 LocalSocket socket = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800108
109 try {
110 socket = new LocalSocket();
111 LocalSocketAddress address = new LocalSocketAddress(mSocket,
112 LocalSocketAddress.Namespace.RESERVED);
113
114 socket.connect(address);
San Mehat67bd2cd2010-01-12 12:18:49 -0800115
116 InputStream inputStream = socket.getInputStream();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800117 synchronized (mDaemonLock) {
118 mOutputStream = socket.getOutputStream();
119 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800120
anga030bc882011-02-01 14:10:25 +0100121 mCallbacks.onDaemonConnected();
122
Kenny Root961aa8c2010-03-22 18:02:45 -0700123 byte[] buffer = new byte[BUFFER_SIZE];
124 int start = 0;
San Mehat67bd2cd2010-01-12 12:18:49 -0800125
126 while (true) {
Kenny Root961aa8c2010-03-22 18:02:45 -0700127 int count = inputStream.read(buffer, start, BUFFER_SIZE - start);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800128 if (count < 0) {
129 loge("got " + count + " reading with start = " + start);
130 break;
131 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800132
Kenny Root12da9d72010-09-02 22:18:14 -0700133 // Add our starting point to the count and reset the start.
134 count += start;
135 start = 0;
136
San Mehat67bd2cd2010-01-12 12:18:49 -0800137 for (int i = 0; i < count; i++) {
138 if (buffer[i] == 0) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800139 final String rawEvent = new String(
140 buffer, start, i - start, Charsets.UTF_8);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800141 log("RCV <- {" + rawEvent + "}");
San Mehat67bd2cd2010-01-12 12:18:49 -0800142
San Mehat67bd2cd2010-01-12 12:18:49 -0800143 try {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800144 final NativeDaemonEvent event = NativeDaemonEvent.parseRawEvent(
145 rawEvent);
146 if (event.isClassUnsolicited()) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800147 // TODO: migrate to sending NativeDaemonEvent instances
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800148 mCallbackHandler.sendMessage(mCallbackHandler.obtainMessage(
149 event.getCode(), event.getRawEvent()));
Irfan Sheriff1cd94ef2011-01-16 14:31:55 -0800150 } else {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800151 mResponseQueue.add(event.getCmdNumber(), event);
San Mehat67bd2cd2010-01-12 12:18:49 -0800152 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800153 } catch (IllegalArgumentException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800154 log("Problem parsing message: " + rawEvent + " - " + e);
San Mehat67bd2cd2010-01-12 12:18:49 -0800155 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800156
San Mehat67bd2cd2010-01-12 12:18:49 -0800157 start = i + 1;
158 }
159 }
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800160 if (start == 0) {
161 final String rawEvent = new String(buffer, start, count, Charsets.UTF_8);
162 log("RCV incomplete <- {" + rawEvent + "}");
163 }
Kenny Root12da9d72010-09-02 22:18:14 -0700164
165 // We should end at the amount we read. If not, compact then
166 // buffer and read again.
Kenny Root961aa8c2010-03-22 18:02:45 -0700167 if (start != count) {
168 final int remaining = BUFFER_SIZE - start;
169 System.arraycopy(buffer, start, buffer, 0, remaining);
170 start = remaining;
171 } else {
172 start = 0;
173 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800174 }
175 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800176 loge("Communications error: " + ex);
San Mehat4c27e0e2010-01-29 05:22:17 -0800177 throw ex;
178 } finally {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700179 synchronized (mDaemonLock) {
San Mehat4c27e0e2010-01-29 05:22:17 -0800180 if (mOutputStream != null) {
181 try {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800182 loge("closing stream for " + mSocket);
San Mehat4c27e0e2010-01-29 05:22:17 -0800183 mOutputStream.close();
184 } catch (IOException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800185 loge("Failed closing output stream: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -0800186 }
187 mOutputStream = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800188 }
San Mehat4c27e0e2010-01-29 05:22:17 -0800189 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800190
San Mehat4c27e0e2010-01-29 05:22:17 -0800191 try {
192 if (socket != null) {
193 socket.close();
194 }
195 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800196 loge("Failed closing socket: " + ex);
San Mehat67bd2cd2010-01-12 12:18:49 -0800197 }
198 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800199 }
200
San Mehat67bd2cd2010-01-12 12:18:49 -0800201 /**
Robert Greenwalt470007f2012-02-07 11:36:55 -0800202 * Make command for daemon, escaping arguments as needed.
San Mehat67bd2cd2010-01-12 12:18:49 -0800203 */
Robert Greenwaltd1925982012-03-12 15:37:40 -0700204 private void makeCommand(StringBuilder builder, String cmd, Object... args)
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700205 throws NativeDaemonConnectorException {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800206 // TODO: eventually enforce that cmd doesn't contain arguments
207 if (cmd.indexOf('\0') >= 0) {
208 throw new IllegalArgumentException("unexpected command: " + cmd);
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700209 }
210
Robert Greenwaltd1925982012-03-12 15:37:40 -0700211 builder.append(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800212 for (Object arg : args) {
213 final String argString = String.valueOf(arg);
214 if (argString.indexOf('\0') >= 0) {
215 throw new IllegalArgumentException("unexpected argument: " + arg);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700216 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800217
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800218 builder.append(' ');
219 appendEscaped(builder, argString);
220 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800221 }
San Mehatdeba6932010-01-20 15:14:31 -0800222
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700223 /**
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800224 * Issue the given command to the native daemon and return a single expected
225 * response.
226 *
227 * @throws NativeDaemonConnectorException when problem communicating with
228 * native daemon, or if the response matches
229 * {@link NativeDaemonEvent#isClassClientError()} or
230 * {@link NativeDaemonEvent#isClassServerError()}.
San Mehatdeba6932010-01-20 15:14:31 -0800231 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800232 public NativeDaemonEvent execute(Command cmd) throws NativeDaemonConnectorException {
233 return execute(cmd.mCmd, cmd.mArguments.toArray());
234 }
235
236 /**
237 * Issue the given command to the native daemon and return a single expected
238 * response.
239 *
240 * @throws NativeDaemonConnectorException when problem communicating with
241 * native daemon, or if the response matches
242 * {@link NativeDaemonEvent#isClassClientError()} or
243 * {@link NativeDaemonEvent#isClassServerError()}.
244 */
245 public NativeDaemonEvent execute(String cmd, Object... args)
246 throws NativeDaemonConnectorException {
247 final NativeDaemonEvent[] events = executeForList(cmd, args);
248 if (events.length != 1) {
249 throw new NativeDaemonConnectorException(
250 "Expected exactly one response, but received " + events.length);
251 }
252 return events[0];
253 }
254
255 /**
256 * Issue the given command to the native daemon and return any
257 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
258 * final terminal response.
259 *
260 * @throws NativeDaemonConnectorException when problem communicating with
261 * native daemon, or if the response matches
262 * {@link NativeDaemonEvent#isClassClientError()} or
263 * {@link NativeDaemonEvent#isClassServerError()}.
264 */
265 public NativeDaemonEvent[] executeForList(Command cmd) throws NativeDaemonConnectorException {
266 return executeForList(cmd.mCmd, cmd.mArguments.toArray());
267 }
268
269 /**
270 * Issue the given command to the native daemon and return any
271 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
272 * final terminal response.
273 *
274 * @throws NativeDaemonConnectorException when problem communicating with
275 * native daemon, or if the response matches
276 * {@link NativeDaemonEvent#isClassClientError()} or
277 * {@link NativeDaemonEvent#isClassServerError()}.
278 */
279 public NativeDaemonEvent[] executeForList(String cmd, Object... args)
San Mehat4c27e0e2010-01-29 05:22:17 -0800280 throws NativeDaemonConnectorException {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800281 return execute(DEFAULT_TIMEOUT, cmd, args);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800282 }
San Mehatdeba6932010-01-20 15:14:31 -0800283
Robert Greenwalt470007f2012-02-07 11:36:55 -0800284 /**
285 * Issue the given command to the native daemon and return any
286 * {@linke NativeDaemonEvent@isClassContinue()} responses, including the
287 * final terminal response. Note that the timeout does not count time in
288 * deep sleep.
289 *
290 * @throws NativeDaemonConnectorException when problem communicating with
291 * native daemon, or if the response matches
292 * {@link NativeDaemonEvent#isClassClientError()} or
293 * {@link NativeDaemonEvent#isClassServerError()}.
294 */
295 public NativeDaemonEvent[] execute(int timeout, String cmd, Object... args)
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800296 throws NativeDaemonConnectorException {
297 final ArrayList<NativeDaemonEvent> events = Lists.newArrayList();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700298
299 final int sequenceNumber = mSequenceNumber.incrementAndGet();
300 final StringBuilder cmdBuilder =
301 new StringBuilder(Integer.toString(sequenceNumber)).append(' ');
302
303 makeCommand(cmdBuilder, cmd, args);
304
305 final String logCmd = cmdBuilder.toString(); /* includes cmdNum, cmd, args */
306 log("SND -> {" + logCmd + "}");
307
308 cmdBuilder.append('\0');
309 final String sentCmd = cmdBuilder.toString(); /* logCmd + \0 */
310
311 synchronized (mDaemonLock) {
312 if (mOutputStream == null) {
313 throw new NativeDaemonConnectorException("missing output stream");
314 } else {
315 try {
316 mOutputStream.write(sentCmd.getBytes(Charsets.UTF_8));
317 } catch (IOException e) {
318 throw new NativeDaemonConnectorException("problem sending command", e);
319 }
320 }
321 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800322
323 NativeDaemonEvent event = null;
324 do {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700325 event = mResponseQueue.remove(sequenceNumber, timeout, sentCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800326 if (event == null) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700327 loge("timed-out waiting for response to " + logCmd);
328 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800329 }
330 events.add(event);
331 } while (event.isClassContinue());
332
333 if (event.isClassClientError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700334 throw new NativeDaemonArgumentException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800335 }
336 if (event.isClassServerError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700337 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800338 }
339
340 return events.toArray(new NativeDaemonEvent[events.size()]);
341 }
342
343 /**
344 * Issue a command to the native daemon and return the raw responses.
345 *
346 * @deprecated callers should move to {@link #execute(String, Object...)}
347 * which returns parsed {@link NativeDaemonEvent}.
348 */
349 @Deprecated
350 public ArrayList<String> doCommand(String cmd) throws NativeDaemonConnectorException {
351 final ArrayList<String> rawEvents = Lists.newArrayList();
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800352 final NativeDaemonEvent[] events = executeForList(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800353 for (NativeDaemonEvent event : events) {
354 rawEvents.add(event.getRawEvent());
355 }
356 return rawEvents;
357 }
358
359 /**
360 * Issues a list command and returns the cooked list of all
361 * {@link NativeDaemonEvent#getMessage()} which match requested code.
362 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800363 @Deprecated
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800364 public String[] doListCommand(String cmd, int expectedCode)
365 throws NativeDaemonConnectorException {
366 final ArrayList<String> list = Lists.newArrayList();
367
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800368 final NativeDaemonEvent[] events = executeForList(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800369 for (int i = 0; i < events.length - 1; i++) {
370 final NativeDaemonEvent event = events[i];
371 final int code = event.getCode();
372 if (code == expectedCode) {
373 list.add(event.getMessage());
374 } else {
San Mehat4c27e0e2010-01-29 05:22:17 -0800375 throw new NativeDaemonConnectorException(
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800376 "unexpected list response " + code + " instead of " + expectedCode);
San Mehatdeba6932010-01-20 15:14:31 -0800377 }
378 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800379
380 final NativeDaemonEvent finalEvent = events[events.length - 1];
381 if (!finalEvent.isClassOk()) {
382 throw new NativeDaemonConnectorException("unexpected final event: " + finalEvent);
383 }
384
385 return list.toArray(new String[list.size()]);
386 }
387
388 /**
389 * Append the given argument to {@link StringBuilder}, escaping as needed,
390 * and surrounding with quotes when it contains spaces.
391 */
392 // @VisibleForTesting
393 static void appendEscaped(StringBuilder builder, String arg) {
394 final boolean hasSpaces = arg.indexOf(' ') >= 0;
395 if (hasSpaces) {
396 builder.append('"');
397 }
398
399 final int length = arg.length();
400 for (int i = 0; i < length; i++) {
401 final char c = arg.charAt(i);
402
403 if (c == '"') {
404 builder.append("\\\"");
405 } else if (c == '\\') {
406 builder.append("\\\\");
407 } else {
408 builder.append(c);
409 }
410 }
411
412 if (hasSpaces) {
413 builder.append('"');
414 }
415 }
416
417 private static class NativeDaemonArgumentException extends NativeDaemonConnectorException {
418 public NativeDaemonArgumentException(String command, NativeDaemonEvent event) {
419 super(command, event);
420 }
421
422 @Override
423 public IllegalArgumentException rethrowAsParcelableException() {
424 throw new IllegalArgumentException(getMessage(), this);
425 }
426 }
427
428 private static class NativeDaemonFailureException extends NativeDaemonConnectorException {
429 public NativeDaemonFailureException(String command, NativeDaemonEvent event) {
430 super(command, event);
431 }
San Mehatdeba6932010-01-20 15:14:31 -0800432 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700433
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800434 /**
435 * Command builder that handles argument list building.
436 */
437 public static class Command {
438 private String mCmd;
439 private ArrayList<Object> mArguments = Lists.newArrayList();
440
441 public Command(String cmd, Object... args) {
442 mCmd = cmd;
443 for (Object arg : args) {
444 appendArg(arg);
445 }
446 }
447
448 public Command appendArg(Object arg) {
449 mArguments.add(arg);
450 return this;
451 }
452 }
453
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700454 /** {@inheritDoc} */
455 public void monitor() {
456 synchronized (mDaemonLock) { }
457 }
Robert Greenwalt470fd722012-01-18 12:51:15 -0800458
459 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
460 mLocalLog.dump(fd, pw, args);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800461 pw.println();
462 mResponseQueue.dump(fd, pw, args);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800463 }
464
465 private void log(String logstring) {
466 if (LOGD) Slog.d(TAG, logstring);
467 mLocalLog.log(logstring);
468 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800469
470 private void loge(String logstring) {
471 Slog.e(TAG, logstring);
472 mLocalLog.log(logstring);
473 }
474
475 private static class ResponseQueue {
476
477 private static class Response {
478 public int cmdNum;
479 public LinkedList<NativeDaemonEvent> responses = new LinkedList<NativeDaemonEvent>();
480 public String request;
481 public Response(int c, String r) {cmdNum = c; request = r;}
482 }
483
484 private final LinkedList<Response> mResponses;
485 private int mMaxCount;
486
487 ResponseQueue(int maxCount) {
488 mResponses = new LinkedList<Response>();
489 mMaxCount = maxCount;
490 }
491
492 public void add(int cmdNum, NativeDaemonEvent response) {
493 Response found = null;
494 synchronized (mResponses) {
495 for (Response r : mResponses) {
496 if (r.cmdNum == cmdNum) {
497 found = r;
498 break;
499 }
500 }
501 if (found == null) {
502 // didn't find it - make sure our queue isn't too big before adding
503 // another..
504 while (mResponses.size() >= mMaxCount) {
505 Slog.e("NativeDaemonConnector.ResponseQueue",
506 "more buffered than allowed: " + mResponses.size() +
507 " >= " + mMaxCount);
508 // let any waiter timeout waiting for this
509 Response r = mResponses.remove();
510 Slog.e("NativeDaemonConnector.ResponseQueue",
511 "Removing request: " + r.request + " (" + r.cmdNum + ")");
512 }
513 found = new Response(cmdNum, null);
514 mResponses.add(found);
515 }
516 found.responses.add(response);
517 }
518 synchronized (found) {
519 found.notify();
520 }
521 }
522
523 // note that the timeout does not count time in deep sleep. If you don't want
524 // the device to sleep, hold a wakelock
525 public NativeDaemonEvent remove(int cmdNum, int timeoutMs, String origCmd) {
526 long endTime = SystemClock.uptimeMillis() + timeoutMs;
527 long nowTime;
528 Response found = null;
529 while (true) {
530 synchronized (mResponses) {
531 for (Response response : mResponses) {
532 if (response.cmdNum == cmdNum) {
533 found = response;
534 // how many response fragments are left
535 switch (response.responses.size()) {
536 case 0: // haven't got any - must wait
537 break;
538 case 1: // last one - remove this from the master list
539 mResponses.remove(response); // fall through
540 default: // take one and move on
541 response.request = origCmd;
542 return response.responses.remove();
543 }
544 }
545 }
546 nowTime = SystemClock.uptimeMillis();
547 if (endTime <= nowTime) {
548 Slog.e("NativeDaemonConnector.ResponseQueue",
549 "Timeout waiting for response");
550 return null;
551 }
552 /* pre-allocate so we have something unique to wait on */
553 if (found == null) {
554 found = new Response(cmdNum, origCmd);
555 mResponses.add(found);
556 }
557 }
558 try {
559 synchronized (found) {
560 found.wait(endTime - nowTime);
561 }
562 } catch (InterruptedException e) {
563 // loop around to check if we're done or if it's time to stop waiting
564 }
565 }
566 }
567
568 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
569 pw.println("Pending requests:");
570 synchronized (mResponses) {
571 for (Response response : mResponses) {
572 pw.println(" Cmd " + response.cmdNum + " - " + response.request);
573 }
574 }
575 }
576 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800577}