blob: abcd8eeb35e25c0f3fabfd18a1f0150c5f8c20ab [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;
Chia-chi Yehe5750a32011-08-03 14:42:11 -070022import android.os.Message;
San Mehat67bd2cd2010-01-12 12:18:49 -080023import android.os.SystemClock;
Robert Greenwalt470fd722012-01-18 12:51:15 -080024import android.util.LocalLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080025import android.util.Slog;
San Mehat67bd2cd2010-01-12 12:18:49 -080026
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080027import com.android.internal.annotations.VisibleForTesting;
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;
Robert Greenwaltef215992012-06-05 11:48:40 -070038import java.util.concurrent.ArrayBlockingQueue;
39import java.util.concurrent.BlockingQueue;
40import java.util.concurrent.TimeUnit;
Robert Greenwalt470007f2012-02-07 11:36:55 -080041import java.util.LinkedList;
San Mehat67bd2cd2010-01-12 12:18:49 -080042
43/**
Jeff Sharkey31c6e482011-11-18 17:09:01 -080044 * Generic connector class for interfacing with a native daemon which uses the
45 * {@code libsysutils} FrameworkListener protocol.
San Mehat67bd2cd2010-01-12 12:18:49 -080046 */
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070047final class NativeDaemonConnector implements Runnable, Handler.Callback, Watchdog.Monitor {
Jeff Sharkey31c6e482011-11-18 17:09:01 -080048 private static final boolean LOGD = false;
San Mehat67bd2cd2010-01-12 12:18:49 -080049
Jeff Sharkey31c6e482011-11-18 17:09:01 -080050 private final String TAG;
51
52 private String mSocket;
53 private OutputStream mOutputStream;
Robert Greenwalt470fd722012-01-18 12:51:15 -080054 private LocalLog mLocalLog;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080055
Robert Greenwalt470007f2012-02-07 11:36:55 -080056 private final ResponseQueue mResponseQueue;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080057
San Mehat67bd2cd2010-01-12 12:18:49 -080058 private INativeDaemonConnectorCallbacks mCallbacks;
Jeff Sharkey31c6e482011-11-18 17:09:01 -080059 private Handler mCallbackHandler;
San Mehat67bd2cd2010-01-12 12:18:49 -080060
Robert Greenwalt470007f2012-02-07 11:36:55 -080061 private AtomicInteger mSequenceNumber;
62
63 private static final int DEFAULT_TIMEOUT = 1 * 60 * 1000; /* 1 minute */
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070064 private static final long WARN_EXECUTE_DELAY_MS = 500; /* .5 sec */
Robert Greenwalt470007f2012-02-07 11:36:55 -080065
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070066 /** Lock held whenever communicating with native daemon. */
Jeff Sharkey31c6e482011-11-18 17:09:01 -080067 private final Object mDaemonLock = new Object();
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -070068
Kenny Root961aa8c2010-03-22 18:02:45 -070069 private final int BUFFER_SIZE = 4096;
70
Jeff Sharkey31c6e482011-11-18 17:09:01 -080071 NativeDaemonConnector(INativeDaemonConnectorCallbacks callbacks, String socket,
Robert Greenwalt470fd722012-01-18 12:51:15 -080072 int responseQueueSize, String logTag, int maxLogSize) {
San Mehat67bd2cd2010-01-12 12:18:49 -080073 mCallbacks = callbacks;
San Mehat67bd2cd2010-01-12 12:18:49 -080074 mSocket = socket;
Robert Greenwalt470007f2012-02-07 11:36:55 -080075 mResponseQueue = new ResponseQueue(responseQueueSize);
76 mSequenceNumber = new AtomicInteger(0);
Jeff Sharkey31c6e482011-11-18 17:09:01 -080077 TAG = logTag != null ? logTag : "NativeDaemonConnector";
Robert Greenwalt470fd722012-01-18 12:51:15 -080078 mLocalLog = new LocalLog(maxLogSize);
San Mehat67bd2cd2010-01-12 12:18:49 -080079 }
80
Chia-chi Yehe5750a32011-08-03 14:42:11 -070081 @Override
San Mehat67bd2cd2010-01-12 12:18:49 -080082 public void run() {
Dianne Hackborn8d044e82013-04-30 17:24:15 -070083 mCallbackHandler = new Handler(FgThread.get().getLooper(), this);
San Mehat67bd2cd2010-01-12 12:18:49 -080084
85 while (true) {
86 try {
87 listenToSocket();
88 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -080089 loge("Error in NativeDaemonConnector: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -080090 SystemClock.sleep(5000);
San Mehat67bd2cd2010-01-12 12:18:49 -080091 }
92 }
93 }
94
Chia-chi Yehe5750a32011-08-03 14:42:11 -070095 @Override
96 public boolean handleMessage(Message msg) {
97 String event = (String) msg.obj;
98 try {
Robert Greenwalt2d34b4a2012-04-20 13:08:02 -070099 if (!mCallbacks.onEvent(msg.what, event, NativeDaemonEvent.unescapeArgs(event))) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800100 log(String.format("Unhandled event '%s'", event));
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700101 }
102 } catch (Exception e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800103 loge("Error handling '" + event + "': " + e);
Chia-chi Yehe5750a32011-08-03 14:42:11 -0700104 }
105 return true;
106 }
107
San Mehat4c27e0e2010-01-29 05:22:17 -0800108 private void listenToSocket() throws IOException {
Kenny Root961aa8c2010-03-22 18:02:45 -0700109 LocalSocket socket = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800110
111 try {
112 socket = new LocalSocket();
113 LocalSocketAddress address = new LocalSocketAddress(mSocket,
114 LocalSocketAddress.Namespace.RESERVED);
115
116 socket.connect(address);
San Mehat67bd2cd2010-01-12 12:18:49 -0800117
118 InputStream inputStream = socket.getInputStream();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800119 synchronized (mDaemonLock) {
120 mOutputStream = socket.getOutputStream();
121 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800122
anga030bc882011-02-01 14:10:25 +0100123 mCallbacks.onDaemonConnected();
124
Kenny Root961aa8c2010-03-22 18:02:45 -0700125 byte[] buffer = new byte[BUFFER_SIZE];
126 int start = 0;
San Mehat67bd2cd2010-01-12 12:18:49 -0800127
128 while (true) {
Kenny Root961aa8c2010-03-22 18:02:45 -0700129 int count = inputStream.read(buffer, start, BUFFER_SIZE - start);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800130 if (count < 0) {
131 loge("got " + count + " reading with start = " + start);
132 break;
133 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800134
Kenny Root12da9d72010-09-02 22:18:14 -0700135 // Add our starting point to the count and reset the start.
136 count += start;
137 start = 0;
138
San Mehat67bd2cd2010-01-12 12:18:49 -0800139 for (int i = 0; i < count; i++) {
140 if (buffer[i] == 0) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800141 final String rawEvent = new String(
142 buffer, start, i - start, Charsets.UTF_8);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800143 log("RCV <- {" + rawEvent + "}");
San Mehat67bd2cd2010-01-12 12:18:49 -0800144
San Mehat67bd2cd2010-01-12 12:18:49 -0800145 try {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800146 final NativeDaemonEvent event = NativeDaemonEvent.parseRawEvent(
147 rawEvent);
148 if (event.isClassUnsolicited()) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800149 // TODO: migrate to sending NativeDaemonEvent instances
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800150 mCallbackHandler.sendMessage(mCallbackHandler.obtainMessage(
151 event.getCode(), event.getRawEvent()));
Irfan Sheriff1cd94ef2011-01-16 14:31:55 -0800152 } else {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800153 mResponseQueue.add(event.getCmdNumber(), event);
San Mehat67bd2cd2010-01-12 12:18:49 -0800154 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800155 } catch (IllegalArgumentException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800156 log("Problem parsing message: " + rawEvent + " - " + e);
San Mehat67bd2cd2010-01-12 12:18:49 -0800157 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800158
San Mehat67bd2cd2010-01-12 12:18:49 -0800159 start = i + 1;
160 }
161 }
Robert Greenwaltf0be1d892012-01-20 16:33:15 -0800162 if (start == 0) {
163 final String rawEvent = new String(buffer, start, count, Charsets.UTF_8);
164 log("RCV incomplete <- {" + rawEvent + "}");
165 }
Kenny Root12da9d72010-09-02 22:18:14 -0700166
167 // We should end at the amount we read. If not, compact then
168 // buffer and read again.
Kenny Root961aa8c2010-03-22 18:02:45 -0700169 if (start != count) {
170 final int remaining = BUFFER_SIZE - start;
171 System.arraycopy(buffer, start, buffer, 0, remaining);
172 start = remaining;
173 } else {
174 start = 0;
175 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800176 }
177 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800178 loge("Communications error: " + ex);
San Mehat4c27e0e2010-01-29 05:22:17 -0800179 throw ex;
180 } finally {
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700181 synchronized (mDaemonLock) {
San Mehat4c27e0e2010-01-29 05:22:17 -0800182 if (mOutputStream != null) {
183 try {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800184 loge("closing stream for " + mSocket);
San Mehat4c27e0e2010-01-29 05:22:17 -0800185 mOutputStream.close();
186 } catch (IOException e) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800187 loge("Failed closing output stream: " + e);
San Mehat4c27e0e2010-01-29 05:22:17 -0800188 }
189 mOutputStream = null;
San Mehat67bd2cd2010-01-12 12:18:49 -0800190 }
San Mehat4c27e0e2010-01-29 05:22:17 -0800191 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800192
San Mehat4c27e0e2010-01-29 05:22:17 -0800193 try {
194 if (socket != null) {
195 socket.close();
196 }
197 } catch (IOException ex) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800198 loge("Failed closing socket: " + ex);
San Mehat67bd2cd2010-01-12 12:18:49 -0800199 }
200 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800201 }
202
San Mehat67bd2cd2010-01-12 12:18:49 -0800203 /**
Robert Greenwalt470007f2012-02-07 11:36:55 -0800204 * Make command for daemon, escaping arguments as needed.
San Mehat67bd2cd2010-01-12 12:18:49 -0800205 */
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800206 private void makeCommand(StringBuilder builder, String cmd, Object... args) {
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800207 if (cmd.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800208 throw new IllegalArgumentException("Unexpected command: " + cmd);
209 }
210 if (cmd.indexOf(' ') >= 0) {
211 throw new IllegalArgumentException("Arguments must be separate from command");
Jeff Sharkeyb0aec072011-10-14 18:32:24 -0700212 }
213
Robert Greenwaltd1925982012-03-12 15:37:40 -0700214 builder.append(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800215 for (Object arg : args) {
216 final String argString = String.valueOf(arg);
217 if (argString.indexOf('\0') >= 0) {
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800218 throw new IllegalArgumentException("Unexpected argument: " + arg);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700219 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800220
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800221 builder.append(' ');
222 appendEscaped(builder, argString);
223 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800224 }
San Mehatdeba6932010-01-20 15:14:31 -0800225
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700226 /**
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800227 * Issue the given command to the native daemon and return a single expected
228 * response.
229 *
230 * @throws NativeDaemonConnectorException when problem communicating with
231 * native daemon, or if the response matches
232 * {@link NativeDaemonEvent#isClassClientError()} or
233 * {@link NativeDaemonEvent#isClassServerError()}.
San Mehatdeba6932010-01-20 15:14:31 -0800234 */
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800235 public NativeDaemonEvent execute(Command cmd) throws NativeDaemonConnectorException {
236 return execute(cmd.mCmd, cmd.mArguments.toArray());
237 }
238
239 /**
240 * Issue the given command to the native daemon and return a single expected
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800241 * response. Any arguments must be separated from base command so they can
242 * be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800243 *
244 * @throws NativeDaemonConnectorException when problem communicating with
245 * native daemon, or if the response matches
246 * {@link NativeDaemonEvent#isClassClientError()} or
247 * {@link NativeDaemonEvent#isClassServerError()}.
248 */
249 public NativeDaemonEvent execute(String cmd, Object... args)
250 throws NativeDaemonConnectorException {
251 final NativeDaemonEvent[] events = executeForList(cmd, args);
252 if (events.length != 1) {
253 throw new NativeDaemonConnectorException(
254 "Expected exactly one response, but received " + events.length);
255 }
256 return events[0];
257 }
258
259 /**
260 * Issue the given command to the native daemon and return any
261 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
262 * final terminal response.
263 *
264 * @throws NativeDaemonConnectorException when problem communicating with
265 * native daemon, or if the response matches
266 * {@link NativeDaemonEvent#isClassClientError()} or
267 * {@link NativeDaemonEvent#isClassServerError()}.
268 */
269 public NativeDaemonEvent[] executeForList(Command cmd) throws NativeDaemonConnectorException {
270 return executeForList(cmd.mCmd, cmd.mArguments.toArray());
271 }
272
273 /**
274 * Issue the given command to the native daemon and return any
275 * {@link NativeDaemonEvent#isClassContinue()} responses, including the
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800276 * final terminal response. Any arguments must be separated from base
277 * command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800278 *
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 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800290 * Issue the given command to the native daemon and return any {@linke
291 * NativeDaemonEvent@isClassContinue()} responses, including the final
292 * terminal response. Note that the timeout does not count time in deep
293 * sleep. Any arguments must be separated from base command so they can be
294 * properly escaped.
Robert Greenwalt470007f2012-02-07 11:36:55 -0800295 *
296 * @throws NativeDaemonConnectorException when problem communicating with
297 * native daemon, or if the response matches
298 * {@link NativeDaemonEvent#isClassClientError()} or
299 * {@link NativeDaemonEvent#isClassServerError()}.
300 */
301 public NativeDaemonEvent[] execute(int timeout, String cmd, Object... args)
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800302 throws NativeDaemonConnectorException {
303 final ArrayList<NativeDaemonEvent> events = Lists.newArrayList();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700304
305 final int sequenceNumber = mSequenceNumber.incrementAndGet();
306 final StringBuilder cmdBuilder =
307 new StringBuilder(Integer.toString(sequenceNumber)).append(' ');
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700308 final long startTime = SystemClock.elapsedRealtime();
Robert Greenwaltd1925982012-03-12 15:37:40 -0700309
310 makeCommand(cmdBuilder, cmd, args);
311
312 final String logCmd = cmdBuilder.toString(); /* includes cmdNum, cmd, args */
313 log("SND -> {" + logCmd + "}");
314
315 cmdBuilder.append('\0');
316 final String sentCmd = cmdBuilder.toString(); /* logCmd + \0 */
317
318 synchronized (mDaemonLock) {
319 if (mOutputStream == null) {
320 throw new NativeDaemonConnectorException("missing output stream");
321 } else {
322 try {
323 mOutputStream.write(sentCmd.getBytes(Charsets.UTF_8));
324 } catch (IOException e) {
325 throw new NativeDaemonConnectorException("problem sending command", e);
326 }
327 }
328 }
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800329
330 NativeDaemonEvent event = null;
331 do {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700332 event = mResponseQueue.remove(sequenceNumber, timeout, sentCmd);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800333 if (event == null) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700334 loge("timed-out waiting for response to " + logCmd);
335 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800336 }
Robert Greenwaltb5aff3f2012-05-15 17:26:57 -0700337 log("RMV <- {" + event + "}");
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800338 events.add(event);
339 } while (event.isClassContinue());
340
Robert Greenwalt5a0c3202012-05-22 16:07:46 -0700341 final long endTime = SystemClock.elapsedRealtime();
342 if (endTime - startTime > WARN_EXECUTE_DELAY_MS) {
343 loge("NDC Command {" + logCmd + "} took too long (" + (endTime - startTime) + "ms)");
344 }
345
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800346 if (event.isClassClientError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700347 throw new NativeDaemonArgumentException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800348 }
349 if (event.isClassServerError()) {
Robert Greenwaltd1925982012-03-12 15:37:40 -0700350 throw new NativeDaemonFailureException(logCmd, event);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800351 }
352
353 return events.toArray(new NativeDaemonEvent[events.size()]);
354 }
355
356 /**
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800357 * Append the given argument to {@link StringBuilder}, escaping as needed,
358 * and surrounding with quotes when it contains spaces.
359 */
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800360 @VisibleForTesting
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800361 static void appendEscaped(StringBuilder builder, String arg) {
362 final boolean hasSpaces = arg.indexOf(' ') >= 0;
363 if (hasSpaces) {
364 builder.append('"');
365 }
366
367 final int length = arg.length();
368 for (int i = 0; i < length; i++) {
369 final char c = arg.charAt(i);
370
371 if (c == '"') {
372 builder.append("\\\"");
373 } else if (c == '\\') {
374 builder.append("\\\\");
375 } else {
376 builder.append(c);
377 }
378 }
379
380 if (hasSpaces) {
381 builder.append('"');
382 }
383 }
384
385 private static class NativeDaemonArgumentException extends NativeDaemonConnectorException {
386 public NativeDaemonArgumentException(String command, NativeDaemonEvent event) {
387 super(command, event);
388 }
389
390 @Override
391 public IllegalArgumentException rethrowAsParcelableException() {
392 throw new IllegalArgumentException(getMessage(), this);
393 }
394 }
395
396 private static class NativeDaemonFailureException extends NativeDaemonConnectorException {
397 public NativeDaemonFailureException(String command, NativeDaemonEvent event) {
398 super(command, event);
399 }
San Mehatdeba6932010-01-20 15:14:31 -0800400 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700401
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800402 /**
Jeff Sharkey7b4596f2013-02-25 10:55:29 -0800403 * Command builder that handles argument list building. Any arguments must
404 * be separated from base command so they can be properly escaped.
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800405 */
406 public static class Command {
407 private String mCmd;
408 private ArrayList<Object> mArguments = Lists.newArrayList();
409
410 public Command(String cmd, Object... args) {
411 mCmd = cmd;
412 for (Object arg : args) {
413 appendArg(arg);
414 }
415 }
416
417 public Command appendArg(Object arg) {
418 mArguments.add(arg);
419 return this;
420 }
421 }
422
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700423 /** {@inheritDoc} */
424 public void monitor() {
425 synchronized (mDaemonLock) { }
426 }
Robert Greenwalt470fd722012-01-18 12:51:15 -0800427
428 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
429 mLocalLog.dump(fd, pw, args);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800430 pw.println();
431 mResponseQueue.dump(fd, pw, args);
Robert Greenwalt470fd722012-01-18 12:51:15 -0800432 }
433
434 private void log(String logstring) {
435 if (LOGD) Slog.d(TAG, logstring);
436 mLocalLog.log(logstring);
437 }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800438
439 private void loge(String logstring) {
440 Slog.e(TAG, logstring);
441 mLocalLog.log(logstring);
442 }
443
444 private static class ResponseQueue {
445
Robert Greenwaltef215992012-06-05 11:48:40 -0700446 private static class PendingCmd {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800447 public int cmdNum;
Robert Greenwaltef215992012-06-05 11:48:40 -0700448 public BlockingQueue<NativeDaemonEvent> responses =
449 new ArrayBlockingQueue<NativeDaemonEvent>(10);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800450 public String request;
Robert Greenwaltef215992012-06-05 11:48:40 -0700451
452 // The availableResponseCount member is used to track when we can remove this
453 // instance from the ResponseQueue.
454 // This is used under the protection of a sync of the mPendingCmds object.
455 // A positive value means we've had more writers retreive this object while
456 // a negative value means we've had more readers. When we've had an equal number
457 // (it goes to zero) we can remove this object from the mPendingCmds list.
458 // Note that we may have more responses for this command (and more readers
459 // coming), but that would result in a new PendingCmd instance being created
460 // and added with the same cmdNum.
461 // Also note that when this goes to zero it just means a parity of readers and
462 // writers have retrieved this object - not that they are done using it. The
463 // responses queue may well have more responses yet to be read or may get more
464 // responses added to it. But all those readers/writers have retreived and
465 // hold references to this instance already so it can be removed from
466 // mPendingCmds queue.
467 public int availableResponseCount;
468 public PendingCmd(int c, String r) {cmdNum = c; request = r;}
Robert Greenwalt470007f2012-02-07 11:36:55 -0800469 }
470
Robert Greenwaltef215992012-06-05 11:48:40 -0700471 private final LinkedList<PendingCmd> mPendingCmds;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800472 private int mMaxCount;
473
474 ResponseQueue(int maxCount) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700475 mPendingCmds = new LinkedList<PendingCmd>();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800476 mMaxCount = maxCount;
477 }
478
479 public void add(int cmdNum, NativeDaemonEvent response) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700480 PendingCmd found = null;
481 synchronized (mPendingCmds) {
482 for (PendingCmd pendingCmd : mPendingCmds) {
483 if (pendingCmd.cmdNum == cmdNum) {
484 found = pendingCmd;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800485 break;
486 }
487 }
488 if (found == null) {
489 // didn't find it - make sure our queue isn't too big before adding
Robert Greenwaltef215992012-06-05 11:48:40 -0700490 while (mPendingCmds.size() >= mMaxCount) {
Robert Greenwalt470007f2012-02-07 11:36:55 -0800491 Slog.e("NativeDaemonConnector.ResponseQueue",
Robert Greenwaltef215992012-06-05 11:48:40 -0700492 "more buffered than allowed: " + mPendingCmds.size() +
Robert Greenwalt470007f2012-02-07 11:36:55 -0800493 " >= " + mMaxCount);
494 // let any waiter timeout waiting for this
Robert Greenwaltef215992012-06-05 11:48:40 -0700495 PendingCmd pendingCmd = mPendingCmds.remove();
Robert Greenwalt470007f2012-02-07 11:36:55 -0800496 Slog.e("NativeDaemonConnector.ResponseQueue",
Robert Greenwaltef215992012-06-05 11:48:40 -0700497 "Removing request: " + pendingCmd.request + " (" +
498 pendingCmd.cmdNum + ")");
Robert Greenwalt470007f2012-02-07 11:36:55 -0800499 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700500 found = new PendingCmd(cmdNum, null);
501 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800502 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700503 found.availableResponseCount++;
504 // if a matching remove call has already retrieved this we can remove this
505 // instance from our list
506 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800507 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700508 try {
509 found.responses.put(response);
510 } catch (InterruptedException e) { }
Robert Greenwalt470007f2012-02-07 11:36:55 -0800511 }
512
513 // note that the timeout does not count time in deep sleep. If you don't want
514 // the device to sleep, hold a wakelock
515 public NativeDaemonEvent remove(int cmdNum, int timeoutMs, String origCmd) {
Robert Greenwaltef215992012-06-05 11:48:40 -0700516 PendingCmd found = null;
517 synchronized (mPendingCmds) {
518 for (PendingCmd pendingCmd : mPendingCmds) {
519 if (pendingCmd.cmdNum == cmdNum) {
520 found = pendingCmd;
521 break;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800522 }
523 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700524 if (found == null) {
525 found = new PendingCmd(cmdNum, origCmd);
526 mPendingCmds.add(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800527 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700528 found.availableResponseCount--;
529 // if a matching add call has already retrieved this we can remove this
530 // instance from our list
531 if (found.availableResponseCount == 0) mPendingCmds.remove(found);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800532 }
Robert Greenwaltef215992012-06-05 11:48:40 -0700533 NativeDaemonEvent result = null;
534 try {
535 result = found.responses.poll(timeoutMs, TimeUnit.MILLISECONDS);
536 } catch (InterruptedException e) {}
537 if (result == null) {
538 Slog.e("NativeDaemonConnector.ResponseQueue", "Timeout waiting for response");
539 }
540 return result;
Robert Greenwalt470007f2012-02-07 11:36:55 -0800541 }
542
543 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
544 pw.println("Pending requests:");
Robert Greenwaltef215992012-06-05 11:48:40 -0700545 synchronized (mPendingCmds) {
546 for (PendingCmd pendingCmd : mPendingCmds) {
547 pw.println(" Cmd " + pendingCmd.cmdNum + " - " + pendingCmd.request);
Robert Greenwalt470007f2012-02-07 11:36:55 -0800548 }
549 }
550 }
551 }
San Mehat67bd2cd2010-01-12 12:18:49 -0800552}