blob: c3f2afa04bf7fda2bdaa64d70afb2bc82df3fdad [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 */
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800209 private void makeCommand(StringBuilder builder, String cmd, Object... args) {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800210 if (cmd.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800211 throw new IllegalArgumentException("Unexpected command: " + cmd);
212 }
213 if (cmd.indexOf(' ') >= 0) {
214 throw new IllegalArgumentException("Arguments must be separate from command");
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700215 }
216
Robert Greenwaltd1925982012-03-12 15:37:40 -0700217 builder.append(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800218 for (Object arg : args) {
219 final String argString = String.valueOf(arg);
220 if (argString.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800221 throw new IllegalArgumentException("Unexpected argument: " + arg);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700222 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800223
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800224 builder.append(' ');
225 appendEscaped(builder, argString);
226 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800227 }
San Mehatdeba6932010-01-20 15:14:31 -0800228
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700229 /**
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800230 * Issue the given command to the native daemon and return a single expected
231 * response.
232 *
233 * @throws NativeDaemonConnectorException when problem communicating with
234 * native daemon, or if the response matches
235 * {@link NativeDaemonEvent#isClassClientError()} or
236 * {@link NativeDaemonEvent#isClassServerError()}.
San Mehatdeba6932010-01-20 15:14:31 -0800237 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800238 public NativeDaemonEvent execute(Command cmd) throws NativeDaemonConnectorException {
239 return execute(cmd.mCmd, cmd.mArguments.toArray());
240 }
241
242 /**
243 * Issue the given command to the native daemon and return a single expected
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800244 * response. Any arguments must be separated from base command so they can
245 * be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800246 *
247 * @throws NativeDaemonConnectorException when problem communicating with
248 * native daemon, or if the response matches
249 * {@link NativeDaemonEvent#isClassClientError()} or
250 * {@link NativeDaemonEvent#isClassServerError()}.
251 */
252 public NativeDaemonEvent execute(String cmd, Object... args)
253 throws NativeDaemonConnectorException {
254 final NativeDaemonEvent[] events = executeForList(cmd, args);
255 if (events.length != 1) {
256 throw new NativeDaemonConnectorException(
257 "Expected exactly one response, but received " + events.length);
258 }
259 return events[0];
260 }
261
262 /**
263 * Issue the given command to the native daemon and return any
264 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
265 * final terminal response.
266 *
267 * @throws NativeDaemonConnectorException when problem communicating with
268 * native daemon, or if the response matches
269 * {@link NativeDaemonEvent#isClassClientError()} or
270 * {@link NativeDaemonEvent#isClassServerError()}.
271 */
272 public NativeDaemonEvent[] executeForList(Command cmd) throws NativeDaemonConnectorException {
273 return executeForList(cmd.mCmd, cmd.mArguments.toArray());
274 }
275
276 /**
277 * Issue the given command to the native daemon and return any
278 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800279 * final terminal response. Any arguments must be separated from base
280 * command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800281 *
282 * @throws NativeDaemonConnectorException when problem communicating with
283 * native daemon, or if the response matches
284 * {@link NativeDaemonEvent#isClassClientError()} or
285 * {@link NativeDaemonEvent#isClassServerError()}.
286 */
287 public NativeDaemonEvent[] executeForList(String cmd, Object... args)
San Mehat4c27e0e2010-01-29 05:22:17 -0800288 throws NativeDaemonConnectorException {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800289 return execute(DEFAULT_TIMEOUT, cmd, args);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800290 }
San Mehatdeba6932010-01-20 15:14:31 -0800291
Robert Greenwalt470007f2012-02-07 11:36:55 -0800292 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800293 * Issue the given command to the native daemon and return any {@linke
294 * NativeDaemonEvent@isClassContinue()} responses, including the final
295 * terminal response. Note that the timeout does not count time in deep
296 * sleep. Any arguments must be separated from base command so they can be
297 * properly escaped.
Robert Greenwalt470007f2012-02-07 11:36:55 -0800298 *
299 * @throws NativeDaemonConnectorException when problem communicating with
300 * native daemon, or if the response matches
301 * {@link NativeDaemonEvent#isClassClientError()} or
302 * {@link NativeDaemonEvent#isClassServerError()}.
303 */
304 public NativeDaemonEvent[] execute(int timeout, String cmd, Object... args)
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800305 throws NativeDaemonConnectorException {
306 final ArrayList<NativeDaemonEvent> events = Lists.newArrayList();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700307
308 final int sequenceNumber = mSequenceNumber.incrementAndGet();
309 final StringBuilder cmdBuilder =
310 new StringBuilder(Integer.toString(sequenceNumber)).append(' ');
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700311 final long startTime = SystemClock.elapsedRealtime();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700312
313 makeCommand(cmdBuilder, cmd, args);
314
315 final String logCmd = cmdBuilder.toString(); /* includes cmdNum, cmd, args */
316 log("SND -> {" + logCmd + "}");
317
318 cmdBuilder.append('\0');
319 final String sentCmd = cmdBuilder.toString(); /* logCmd + \0 */
320
321 synchronized (mDaemonLock) {
322 if (mOutputStream == null) {
323 throw new NativeDaemonConnectorException("missing output stream");
324 } else {
325 try {
326 mOutputStream.write(sentCmd.getBytes(Charsets.UTF_8));
327 } catch (IOException e) {
328 throw new NativeDaemonConnectorException("problem sending command", e);
329 }
330 }
331 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800332
333 NativeDaemonEvent event = null;
334 do {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700335 event = mResponseQueue.remove(sequenceNumber, timeout, sentCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800336 if (event == null) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700337 loge("timed-out waiting for response to " + logCmd);
338 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800339 }
Robert Greenwaltb5aff3f2012-05-15 17:26:57 -0700340 log("RMV <- {" + event + "}");
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800341 events.add(event);
342 } while (event.isClassContinue());
343
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700344 final long endTime = SystemClock.elapsedRealtime();
345 if (endTime - startTime > WARN_EXECUTE_DELAY_MS) {
346 loge("NDC Command {" + logCmd + "} took too long (" + (endTime - startTime) + "ms)");
347 }
348
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800349 if (event.isClassClientError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700350 throw new NativeDaemonArgumentException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800351 }
352 if (event.isClassServerError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700353 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800354 }
355
356 return events.toArray(new NativeDaemonEvent[events.size()]);
357 }
358
359 /**
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800360 * Append the given argument to {@link StringBuilder}, escaping as needed,
361 * and surrounding with quotes when it contains spaces.
362 */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800363 @VisibleForTesting
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800364 static void appendEscaped(StringBuilder builder, String arg) {
365 final boolean hasSpaces = arg.indexOf(' ') >= 0;
366 if (hasSpaces) {
367 builder.append('"');
368 }
369
370 final int length = arg.length();
371 for (int i = 0; i < length; i++) {
372 final char c = arg.charAt(i);
373
374 if (c == '"') {
375 builder.append("\\\"");
376 } else if (c == '\\') {
377 builder.append("\\\\");
378 } else {
379 builder.append(c);
380 }
381 }
382
383 if (hasSpaces) {
384 builder.append('"');
385 }
386 }
387
388 private static class NativeDaemonArgumentException extends NativeDaemonConnectorException {
389 public NativeDaemonArgumentException(String command, NativeDaemonEvent event) {
390 super(command, event);
391 }
392
393 @Override
394 public IllegalArgumentException rethrowAsParcelableException() {
395 throw new IllegalArgumentException(getMessage(), this);
396 }
397 }
398
399 private static class NativeDaemonFailureException extends NativeDaemonConnectorException {
400 public NativeDaemonFailureException(String command, NativeDaemonEvent event) {
401 super(command, event);
402 }
San Mehatdeba6932010-01-20 15:14:31 -0800403 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700404
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800405 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800406 * Command builder that handles argument list building. Any arguments must
407 * be separated from base command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800408 */
409 public static class Command {
410 private String mCmd;
411 private ArrayList<Object> mArguments = Lists.newArrayList();
412
413 public Command(String cmd, Object... args) {
414 mCmd = cmd;
415 for (Object arg : args) {
416 appendArg(arg);
417 }
418 }
419
420 public Command appendArg(Object arg) {
421 mArguments.add(arg);
422 return this;
423 }
424 }
425
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700426 /** {@inheritDoc} */
427 public void monitor() {
428 synchronized (mDaemonLock) { }
429 }
Robert Greenwalt470fd722012-01-18 12:51:15 -0800430
431 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
432 mLocalLog.dump(fd, pw, args);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800433 pw.println();
434 mResponseQueue.dump(fd, pw, args);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800435 }
436
437 private void log(String logstring) {
438 if (LOGD) Slog.d(TAG, logstring);
439 mLocalLog.log(logstring);
440 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800441
442 private void loge(String logstring) {
443 Slog.e(TAG, logstring);
444 mLocalLog.log(logstring);
445 }
446
447 private static class ResponseQueue {
448
Robert Greenwaltef215992012-06-05 11:48:40 -0700449 private static class PendingCmd {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800450 public int cmdNum;
Robert Greenwaltef215992012-06-05 11:48:40 -0700451 public BlockingQueue<NativeDaemonEvent> responses =
452 new ArrayBlockingQueue<NativeDaemonEvent>(10);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800453 public String request;
Robert Greenwaltef215992012-06-05 11:48:40 -0700454
455 // The availableResponseCount member is used to track when we can remove this
456 // instance from the ResponseQueue.
457 // This is used under the protection of a sync of the mPendingCmds object.
458 // A positive value means we've had more writers retreive this object while
459 // a negative value means we've had more readers. When we've had an equal number
460 // (it goes to zero) we can remove this object from the mPendingCmds list.
461 // Note that we may have more responses for this command (and more readers
462 // coming), but that would result in a new PendingCmd instance being created
463 // and added with the same cmdNum.
464 // Also note that when this goes to zero it just means a parity of readers and
465 // writers have retrieved this object - not that they are done using it. The
466 // responses queue may well have more responses yet to be read or may get more
467 // responses added to it. But all those readers/writers have retreived and
468 // hold references to this instance already so it can be removed from
469 // mPendingCmds queue.
470 public int availableResponseCount;
471 public PendingCmd(int c, String r) {cmdNum = c; request = r;}
Robert Greenwalt470007f2012-02-07 11:36:55 -0800472 }
473
Robert Greenwaltef215992012-06-05 11:48:40 -0700474 private final LinkedList<PendingCmd> mPendingCmds;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800475 private int mMaxCount;
476
477 ResponseQueue(int maxCount) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700478 mPendingCmds = new LinkedList<PendingCmd>();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800479 mMaxCount = maxCount;
480 }
481
482 public void add(int cmdNum, NativeDaemonEvent response) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700483 PendingCmd found = null;
484 synchronized (mPendingCmds) {
485 for (PendingCmd pendingCmd : mPendingCmds) {
486 if (pendingCmd.cmdNum == cmdNum) {
487 found = pendingCmd;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800488 break;
489 }
490 }
491 if (found == null) {
492 // didn't find it - make sure our queue isn't too big before adding
Robert Greenwaltef215992012-06-05 11:48:40 -0700493 while (mPendingCmds.size() >= mMaxCount) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800494 Slog.e("NativeDaemonConnector.ResponseQueue",
Robert Greenwaltef215992012-06-05 11:48:40 -0700495 "more buffered than allowed: " + mPendingCmds.size() +
Robert Greenwalt470007f2012-02-07 11:36:55 -0800496 " >= " + mMaxCount);
497 // let any waiter timeout waiting for this
Robert Greenwaltef215992012-06-05 11:48:40 -0700498 PendingCmd pendingCmd = mPendingCmds.remove();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800499 Slog.e("NativeDaemonConnector.ResponseQueue",
Robert Greenwaltef215992012-06-05 11:48:40 -0700500 "Removing request: " + pendingCmd.request + " (" +
501 pendingCmd.cmdNum + ")");
Robert Greenwalt470007f2012-02-07 11:36:55 -0800502 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700503 found = new PendingCmd(cmdNum, null);
504 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800505 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700506 found.availableResponseCount++;
507 // if a matching remove call has already retrieved this we can remove this
508 // instance from our list
509 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800510 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700511 try {
512 found.responses.put(response);
513 } catch (InterruptedException e) { }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800514 }
515
516 // note that the timeout does not count time in deep sleep. If you don't want
517 // the device to sleep, hold a wakelock
518 public NativeDaemonEvent remove(int cmdNum, int timeoutMs, String origCmd) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700519 PendingCmd found = null;
520 synchronized (mPendingCmds) {
521 for (PendingCmd pendingCmd : mPendingCmds) {
522 if (pendingCmd.cmdNum == cmdNum) {
523 found = pendingCmd;
524 break;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800525 }
526 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700527 if (found == null) {
528 found = new PendingCmd(cmdNum, origCmd);
529 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800530 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700531 found.availableResponseCount--;
532 // if a matching add call has already retrieved this we can remove this
533 // instance from our list
534 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800535 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700536 NativeDaemonEvent result = null;
537 try {
538 result = found.responses.poll(timeoutMs, TimeUnit.MILLISECONDS);
539 } catch (InterruptedException e) {}
540 if (result == null) {
541 Slog.e("NativeDaemonConnector.ResponseQueue", "Timeout waiting for response");
542 }
543 return result;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800544 }
545
546 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
547 pw.println("Pending requests:");
Robert Greenwaltef215992012-06-05 11:48:40 -0700548 synchronized (mPendingCmds) {
549 for (PendingCmd pendingCmd : mPendingCmds) {
550 pw.println(" Cmd " + pendingCmd.cmdNum + " - " + pendingCmd.request);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800551 }
552 }
553 }
554 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800555}