blob: a15d3bbb4cf2a8dab26f398278273f6d1a20183b [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 Greenwaltb5aff3f2012-05-15 17:26:57 -0700151 log("POST<- {" + rawEvent + "}");
Robert Greenwalt470007f2012-02-07 11:36:55 -0800152 mResponseQueue.add(event.getCmdNumber(), event);
San Mehat67bd2cd2010-01-12 12:18:49 -0800153 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800154 } catch (IllegalArgumentException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800155 log("Problem parsing message: " + rawEvent + " - " + e);
San Mehat67bd2cd2010-01-12 12:18:49 -0800156 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800157
San Mehat67bd2cd2010-01-12 12:18:49 -0800158 start = i + 1;
159 }
160 }
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800161 if (start == 0) {
162 final String rawEvent = new String(buffer, start, count, Charsets.UTF_8);
163 log("RCV incomplete <- {" + rawEvent + "}");
164 }
Kenny Root12da9d72010-09-02 22:18:14 -0700165
166 // We should end at the amount we read. If not, compact then
167 // buffer and read again.
Kenny Root961aa8c2010-03-22 18:02:45 -0700168 if (start != count) {
169 final int remaining = BUFFER_SIZE - start;
170 System.arraycopy(buffer, start, buffer, 0, remaining);
171 start = remaining;
172 } else {
173 start = 0;
174 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800175 }
176 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800177 loge("Communications error: " + ex);
San Mehat4c27e0e2010-01-29 05:22:17 -0800178 throw ex;
179 } finally {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700180 synchronized (mDaemonLock) {
San Mehat4c27e0e2010-01-29 05:22:17 -0800181 if (mOutputStream != null) {
182 try {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800183 loge("closing stream for " + mSocket);
San Mehat4c27e0e2010-01-29 05:22:17 -0800184 mOutputStream.close();
185 } catch (IOException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800186 loge("Failed closing output stream: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -0800187 }
188 mOutputStream = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800189 }
San Mehat4c27e0e2010-01-29 05:22:17 -0800190 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800191
San Mehat4c27e0e2010-01-29 05:22:17 -0800192 try {
193 if (socket != null) {
194 socket.close();
195 }
196 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800197 loge("Failed closing socket: " + ex);
San Mehat67bd2cd2010-01-12 12:18:49 -0800198 }
199 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800200 }
201
San Mehat67bd2cd2010-01-12 12:18:49 -0800202 /**
Robert Greenwalt470007f2012-02-07 11:36:55 -0800203 * Make command for daemon, escaping arguments as needed.
San Mehat67bd2cd2010-01-12 12:18:49 -0800204 */
Robert Greenwaltd1925982012-03-12 15:37:40 -0700205 private void makeCommand(StringBuilder builder, String cmd, Object... args)
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700206 throws NativeDaemonConnectorException {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800207 // TODO: eventually enforce that cmd doesn't contain arguments
208 if (cmd.indexOf('\0') >= 0) {
209 throw new IllegalArgumentException("unexpected command: " + cmd);
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700210 }
211
Robert Greenwaltd1925982012-03-12 15:37:40 -0700212 builder.append(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800213 for (Object arg : args) {
214 final String argString = String.valueOf(arg);
215 if (argString.indexOf('\0') >= 0) {
216 throw new IllegalArgumentException("unexpected argument: " + arg);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700217 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800218
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800219 builder.append(' ');
220 appendEscaped(builder, argString);
221 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800222 }
San Mehatdeba6932010-01-20 15:14:31 -0800223
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700224 /**
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800225 * Issue the given command to the native daemon and return a single expected
226 * response.
227 *
228 * @throws NativeDaemonConnectorException when problem communicating with
229 * native daemon, or if the response matches
230 * {@link NativeDaemonEvent#isClassClientError()} or
231 * {@link NativeDaemonEvent#isClassServerError()}.
San Mehatdeba6932010-01-20 15:14:31 -0800232 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800233 public NativeDaemonEvent execute(Command cmd) throws NativeDaemonConnectorException {
234 return execute(cmd.mCmd, cmd.mArguments.toArray());
235 }
236
237 /**
238 * Issue the given command to the native daemon and return a single expected
239 * response.
240 *
241 * @throws NativeDaemonConnectorException when problem communicating with
242 * native daemon, or if the response matches
243 * {@link NativeDaemonEvent#isClassClientError()} or
244 * {@link NativeDaemonEvent#isClassServerError()}.
245 */
246 public NativeDaemonEvent execute(String cmd, Object... args)
247 throws NativeDaemonConnectorException {
248 final NativeDaemonEvent[] events = executeForList(cmd, args);
249 if (events.length != 1) {
250 throw new NativeDaemonConnectorException(
251 "Expected exactly one response, but received " + events.length);
252 }
253 return events[0];
254 }
255
256 /**
257 * Issue the given command to the native daemon and return any
258 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
259 * final terminal response.
260 *
261 * @throws NativeDaemonConnectorException when problem communicating with
262 * native daemon, or if the response matches
263 * {@link NativeDaemonEvent#isClassClientError()} or
264 * {@link NativeDaemonEvent#isClassServerError()}.
265 */
266 public NativeDaemonEvent[] executeForList(Command cmd) throws NativeDaemonConnectorException {
267 return executeForList(cmd.mCmd, cmd.mArguments.toArray());
268 }
269
270 /**
271 * Issue the given command to the native daemon and return any
272 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
273 * final terminal response.
274 *
275 * @throws NativeDaemonConnectorException when problem communicating with
276 * native daemon, or if the response matches
277 * {@link NativeDaemonEvent#isClassClientError()} or
278 * {@link NativeDaemonEvent#isClassServerError()}.
279 */
280 public NativeDaemonEvent[] executeForList(String cmd, Object... args)
San Mehat4c27e0e2010-01-29 05:22:17 -0800281 throws NativeDaemonConnectorException {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800282 return execute(DEFAULT_TIMEOUT, cmd, args);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800283 }
San Mehatdeba6932010-01-20 15:14:31 -0800284
Robert Greenwalt470007f2012-02-07 11:36:55 -0800285 /**
286 * Issue the given command to the native daemon and return any
287 * {@linke NativeDaemonEvent@isClassContinue()} responses, including the
288 * final terminal response. Note that the timeout does not count time in
289 * deep sleep.
290 *
291 * @throws NativeDaemonConnectorException when problem communicating with
292 * native daemon, or if the response matches
293 * {@link NativeDaemonEvent#isClassClientError()} or
294 * {@link NativeDaemonEvent#isClassServerError()}.
295 */
296 public NativeDaemonEvent[] execute(int timeout, String cmd, Object... args)
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800297 throws NativeDaemonConnectorException {
298 final ArrayList<NativeDaemonEvent> events = Lists.newArrayList();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700299
300 final int sequenceNumber = mSequenceNumber.incrementAndGet();
301 final StringBuilder cmdBuilder =
302 new StringBuilder(Integer.toString(sequenceNumber)).append(' ');
303
304 makeCommand(cmdBuilder, cmd, args);
305
306 final String logCmd = cmdBuilder.toString(); /* includes cmdNum, cmd, args */
307 log("SND -> {" + logCmd + "}");
308
309 cmdBuilder.append('\0');
310 final String sentCmd = cmdBuilder.toString(); /* logCmd + \0 */
311
312 synchronized (mDaemonLock) {
313 if (mOutputStream == null) {
314 throw new NativeDaemonConnectorException("missing output stream");
315 } else {
316 try {
317 mOutputStream.write(sentCmd.getBytes(Charsets.UTF_8));
318 } catch (IOException e) {
319 throw new NativeDaemonConnectorException("problem sending command", e);
320 }
321 }
322 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800323
324 NativeDaemonEvent event = null;
325 do {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700326 event = mResponseQueue.remove(sequenceNumber, timeout, sentCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800327 if (event == null) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700328 loge("timed-out waiting for response to " + logCmd);
329 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800330 }
Robert Greenwaltb5aff3f2012-05-15 17:26:57 -0700331 log("RMV <- {" + event + "}");
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800332 events.add(event);
333 } while (event.isClassContinue());
334
335 if (event.isClassClientError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700336 throw new NativeDaemonArgumentException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800337 }
338 if (event.isClassServerError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700339 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800340 }
341
Robert Greenwaltb5aff3f2012-05-15 17:26:57 -0700342 log("RTN <- {" + logCmd + "}");
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800343 return events.toArray(new NativeDaemonEvent[events.size()]);
344 }
345
346 /**
347 * Issue a command to the native daemon and return the raw responses.
348 *
349 * @deprecated callers should move to {@link #execute(String, Object...)}
350 * which returns parsed {@link NativeDaemonEvent}.
351 */
352 @Deprecated
353 public ArrayList<String> doCommand(String cmd) throws NativeDaemonConnectorException {
354 final ArrayList<String> rawEvents = Lists.newArrayList();
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800355 final NativeDaemonEvent[] events = executeForList(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800356 for (NativeDaemonEvent event : events) {
357 rawEvents.add(event.getRawEvent());
358 }
359 return rawEvents;
360 }
361
362 /**
363 * Issues a list command and returns the cooked list of all
364 * {@link NativeDaemonEvent#getMessage()} which match requested code.
365 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800366 @Deprecated
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800367 public String[] doListCommand(String cmd, int expectedCode)
368 throws NativeDaemonConnectorException {
369 final ArrayList<String> list = Lists.newArrayList();
370
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800371 final NativeDaemonEvent[] events = executeForList(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800372 for (int i = 0; i < events.length - 1; i++) {
373 final NativeDaemonEvent event = events[i];
374 final int code = event.getCode();
375 if (code == expectedCode) {
376 list.add(event.getMessage());
377 } else {
San Mehat4c27e0e2010-01-29 05:22:17 -0800378 throw new NativeDaemonConnectorException(
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800379 "unexpected list response " + code + " instead of " + expectedCode);
San Mehatdeba6932010-01-20 15:14:31 -0800380 }
381 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800382
383 final NativeDaemonEvent finalEvent = events[events.length - 1];
384 if (!finalEvent.isClassOk()) {
385 throw new NativeDaemonConnectorException("unexpected final event: " + finalEvent);
386 }
387
388 return list.toArray(new String[list.size()]);
389 }
390
391 /**
392 * Append the given argument to {@link StringBuilder}, escaping as needed,
393 * and surrounding with quotes when it contains spaces.
394 */
395 // @VisibleForTesting
396 static void appendEscaped(StringBuilder builder, String arg) {
397 final boolean hasSpaces = arg.indexOf(' ') >= 0;
398 if (hasSpaces) {
399 builder.append('"');
400 }
401
402 final int length = arg.length();
403 for (int i = 0; i < length; i++) {
404 final char c = arg.charAt(i);
405
406 if (c == '"') {
407 builder.append("\\\"");
408 } else if (c == '\\') {
409 builder.append("\\\\");
410 } else {
411 builder.append(c);
412 }
413 }
414
415 if (hasSpaces) {
416 builder.append('"');
417 }
418 }
419
420 private static class NativeDaemonArgumentException extends NativeDaemonConnectorException {
421 public NativeDaemonArgumentException(String command, NativeDaemonEvent event) {
422 super(command, event);
423 }
424
425 @Override
426 public IllegalArgumentException rethrowAsParcelableException() {
427 throw new IllegalArgumentException(getMessage(), this);
428 }
429 }
430
431 private static class NativeDaemonFailureException extends NativeDaemonConnectorException {
432 public NativeDaemonFailureException(String command, NativeDaemonEvent event) {
433 super(command, event);
434 }
San Mehatdeba6932010-01-20 15:14:31 -0800435 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700436
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800437 /**
438 * Command builder that handles argument list building.
439 */
440 public static class Command {
441 private String mCmd;
442 private ArrayList<Object> mArguments = Lists.newArrayList();
443
444 public Command(String cmd, Object... args) {
445 mCmd = cmd;
446 for (Object arg : args) {
447 appendArg(arg);
448 }
449 }
450
451 public Command appendArg(Object arg) {
452 mArguments.add(arg);
453 return this;
454 }
455 }
456
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700457 /** {@inheritDoc} */
458 public void monitor() {
459 synchronized (mDaemonLock) { }
460 }
Robert Greenwalt470fd722012-01-18 12:51:15 -0800461
462 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
463 mLocalLog.dump(fd, pw, args);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800464 pw.println();
465 mResponseQueue.dump(fd, pw, args);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800466 }
467
468 private void log(String logstring) {
469 if (LOGD) Slog.d(TAG, logstring);
470 mLocalLog.log(logstring);
471 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800472
473 private void loge(String logstring) {
474 Slog.e(TAG, logstring);
475 mLocalLog.log(logstring);
476 }
477
478 private static class ResponseQueue {
479
480 private static class Response {
481 public int cmdNum;
482 public LinkedList<NativeDaemonEvent> responses = new LinkedList<NativeDaemonEvent>();
483 public String request;
484 public Response(int c, String r) {cmdNum = c; request = r;}
485 }
486
487 private final LinkedList<Response> mResponses;
488 private int mMaxCount;
489
490 ResponseQueue(int maxCount) {
491 mResponses = new LinkedList<Response>();
492 mMaxCount = maxCount;
493 }
494
495 public void add(int cmdNum, NativeDaemonEvent response) {
496 Response found = null;
497 synchronized (mResponses) {
498 for (Response r : mResponses) {
499 if (r.cmdNum == cmdNum) {
500 found = r;
501 break;
502 }
503 }
504 if (found == null) {
505 // didn't find it - make sure our queue isn't too big before adding
506 // another..
507 while (mResponses.size() >= mMaxCount) {
508 Slog.e("NativeDaemonConnector.ResponseQueue",
509 "more buffered than allowed: " + mResponses.size() +
510 " >= " + mMaxCount);
511 // let any waiter timeout waiting for this
512 Response r = mResponses.remove();
513 Slog.e("NativeDaemonConnector.ResponseQueue",
514 "Removing request: " + r.request + " (" + r.cmdNum + ")");
515 }
516 found = new Response(cmdNum, null);
517 mResponses.add(found);
518 }
519 found.responses.add(response);
520 }
521 synchronized (found) {
522 found.notify();
523 }
524 }
525
526 // note that the timeout does not count time in deep sleep. If you don't want
527 // the device to sleep, hold a wakelock
528 public NativeDaemonEvent remove(int cmdNum, int timeoutMs, String origCmd) {
529 long endTime = SystemClock.uptimeMillis() + timeoutMs;
530 long nowTime;
531 Response found = null;
532 while (true) {
533 synchronized (mResponses) {
534 for (Response response : mResponses) {
535 if (response.cmdNum == cmdNum) {
536 found = response;
537 // how many response fragments are left
538 switch (response.responses.size()) {
539 case 0: // haven't got any - must wait
540 break;
541 case 1: // last one - remove this from the master list
542 mResponses.remove(response); // fall through
543 default: // take one and move on
544 response.request = origCmd;
545 return response.responses.remove();
546 }
547 }
548 }
549 nowTime = SystemClock.uptimeMillis();
550 if (endTime <= nowTime) {
551 Slog.e("NativeDaemonConnector.ResponseQueue",
552 "Timeout waiting for response");
553 return null;
554 }
555 /* pre-allocate so we have something unique to wait on */
556 if (found == null) {
557 found = new Response(cmdNum, origCmd);
558 mResponses.add(found);
559 }
560 }
561 try {
562 synchronized (found) {
563 found.wait(endTime - nowTime);
564 }
565 } catch (InterruptedException e) {
566 // loop around to check if we're done or if it's time to stop waiting
567 }
568 }
569 }
570
571 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
572 pw.println("Pending requests:");
573 synchronized (mResponses) {
574 for (Response response : mResponses) {
575 pw.println(" Cmd " + response.cmdNum + " - " + response.request);
576 }
577 }
578 }
579 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800580}