blob: 641c62fe2a4d7b53255a8019096bfd0d722878af [file] [log] [blame]
Hugo Benichieab511b2016-09-09 09:23:47 +09001/*
2 * Copyright (C) 2016 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.connectivity;
18
19import android.content.Context;
20import android.net.ConnectivityMetricsEvent;
21import android.net.IIpConnectivityMetrics;
Michal Karpinskidd9bb4f2016-10-12 14:59:26 +010022import android.net.INetdEventCallback;
Hugo Benichie1c173d2016-10-18 10:36:33 +090023import android.net.metrics.ApfProgramEvent;
Hugo Benichieab511b2016-09-09 09:23:47 +090024import android.net.metrics.IpConnectivityLog;
Michal Karpinskidd9bb4f2016-10-12 14:59:26 +010025import android.os.Binder;
Hugo Benichieab511b2016-09-09 09:23:47 +090026import android.os.IBinder;
27import android.os.Parcelable;
Michal Karpinskidd9bb4f2016-10-12 14:59:26 +010028import android.os.Process;
Hugo Benichi05686db2016-10-19 11:17:28 +090029import android.provider.Settings;
Hugo Benichieab511b2016-09-09 09:23:47 +090030import android.text.TextUtils;
Hugo Benichie1c173d2016-10-18 10:36:33 +090031import android.text.format.DateUtils;
32import android.util.ArrayMap;
Hugo Benichieab511b2016-09-09 09:23:47 +090033import android.util.Base64;
34import android.util.Log;
35import com.android.internal.annotations.GuardedBy;
36import com.android.internal.annotations.VisibleForTesting;
Hugo Benichie1c173d2016-10-18 10:36:33 +090037import com.android.internal.util.TokenBucket;
Hugo Benichieab511b2016-09-09 09:23:47 +090038import com.android.server.SystemService;
39import java.io.FileDescriptor;
40import java.io.IOException;
41import java.io.PrintWriter;
42import java.util.ArrayList;
Hugo Benichi05686db2016-10-19 11:17:28 +090043import java.util.function.ToIntFunction;
Hugo Benichieab511b2016-09-09 09:23:47 +090044
45import static com.android.server.connectivity.metrics.IpConnectivityLogClass.IpConnectivityEvent;
46
47/** {@hide} */
48final public class IpConnectivityMetrics extends SystemService {
49 private static final String TAG = IpConnectivityMetrics.class.getSimpleName();
50 private static final boolean DBG = false;
51
Hugo Benichid680d4c2016-10-13 13:16:16 +090052 // The logical version numbers of ipconnectivity.proto, corresponding to the
53 // "version" field of IpConnectivityLog.
54 private static final int NYC = 0;
55 private static final int NYC_MR1 = 1;
56 private static final int NYC_MR2 = 2;
57 public static final int VERSION = NYC_MR2;
58
Hugo Benichieab511b2016-09-09 09:23:47 +090059 private static final String SERVICE_NAME = IpConnectivityLog.SERVICE_NAME;
60
61 // Default size of the event buffer. Once the buffer is full, incoming events are dropped.
62 private static final int DEFAULT_BUFFER_SIZE = 2000;
Hugo Benichi05686db2016-10-19 11:17:28 +090063 // Maximum size of the event buffer.
64 private static final int MAXIMUM_BUFFER_SIZE = DEFAULT_BUFFER_SIZE * 10;
Hugo Benichieab511b2016-09-09 09:23:47 +090065
Hugo Benichie1c173d2016-10-18 10:36:33 +090066 private static final int ERROR_RATE_LIMITED = -1;
Hugo Benichieab511b2016-09-09 09:23:47 +090067
68 // Lock ensuring that concurrent manipulations of the event buffer are correct.
69 // There are three concurrent operations to synchronize:
70 // - appending events to the buffer.
71 // - iterating throught the buffer.
72 // - flushing the buffer content and replacing it by a new buffer.
73 private final Object mLock = new Object();
74
75 @VisibleForTesting
76 public final Impl impl = new Impl();
Hugo Benichie69608f2016-09-23 14:48:01 +090077 private NetdEventListenerService mNetdListener;
Hugo Benichi00a42d42016-09-13 15:55:09 +090078
Hugo Benichieab511b2016-09-09 09:23:47 +090079 @GuardedBy("mLock")
80 private ArrayList<ConnectivityMetricsEvent> mBuffer;
81 @GuardedBy("mLock")
82 private int mDropped;
83 @GuardedBy("mLock")
84 private int mCapacity;
Hugo Benichie1c173d2016-10-18 10:36:33 +090085 @GuardedBy("mLock")
86 private final ArrayMap<Class<?>, TokenBucket> mBuckets = makeRateLimitingBuckets();
Hugo Benichieab511b2016-09-09 09:23:47 +090087
Hugo Benichi05686db2016-10-19 11:17:28 +090088 private final ToIntFunction<Context> mCapacityGetter;
89
90 public IpConnectivityMetrics(Context ctx, ToIntFunction<Context> capacityGetter) {
Hugo Benichieab511b2016-09-09 09:23:47 +090091 super(ctx);
Hugo Benichi05686db2016-10-19 11:17:28 +090092 mCapacityGetter = capacityGetter;
Hugo Benichieab511b2016-09-09 09:23:47 +090093 initBuffer();
94 }
Hugo Benichieab511b2016-09-09 09:23:47 +090095
96 public IpConnectivityMetrics(Context ctx) {
Hugo Benichi05686db2016-10-19 11:17:28 +090097 this(ctx, READ_BUFFER_SIZE);
Hugo Benichieab511b2016-09-09 09:23:47 +090098 }
99
100 @Override
101 public void onStart() {
102 if (DBG) Log.d(TAG, "onStart");
103 }
104
105 @Override
106 public void onBootPhase(int phase) {
107 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
108 if (DBG) Log.d(TAG, "onBootPhase");
Hugo Benichie69608f2016-09-23 14:48:01 +0900109 mNetdListener = new NetdEventListenerService(getContext());
Hugo Benichieab511b2016-09-09 09:23:47 +0900110
111 publishBinderService(SERVICE_NAME, impl);
Hugo Benichie69608f2016-09-23 14:48:01 +0900112 publishBinderService(mNetdListener.SERVICE_NAME, mNetdListener);
Hugo Benichieab511b2016-09-09 09:23:47 +0900113 }
114 }
115
116 @VisibleForTesting
117 public int bufferCapacity() {
Hugo Benichi05686db2016-10-19 11:17:28 +0900118 return mCapacityGetter.applyAsInt(getContext());
Hugo Benichieab511b2016-09-09 09:23:47 +0900119 }
120
121 private void initBuffer() {
122 synchronized (mLock) {
123 mDropped = 0;
124 mCapacity = bufferCapacity();
125 mBuffer = new ArrayList<>(mCapacity);
126 }
127 }
128
129 private int append(ConnectivityMetricsEvent event) {
130 if (DBG) Log.d(TAG, "logEvent: " + event);
131 synchronized (mLock) {
132 final int left = mCapacity - mBuffer.size();
133 if (event == null) {
134 return left;
135 }
Hugo Benichie1c173d2016-10-18 10:36:33 +0900136 if (isRateLimited(event)) {
137 // Do not count as a dropped event. TODO: consider adding separate counter
138 return ERROR_RATE_LIMITED;
139 }
Hugo Benichieab511b2016-09-09 09:23:47 +0900140 if (left == 0) {
141 mDropped++;
142 return 0;
143 }
144 mBuffer.add(event);
145 return left - 1;
146 }
147 }
148
Hugo Benichie1c173d2016-10-18 10:36:33 +0900149 private boolean isRateLimited(ConnectivityMetricsEvent event) {
150 TokenBucket tb = mBuckets.get(event.data.getClass());
151 return (tb != null) && !tb.get();
152 }
153
Hugo Benichieab511b2016-09-09 09:23:47 +0900154 private String flushEncodedOutput() {
155 final ArrayList<ConnectivityMetricsEvent> events;
156 final int dropped;
157 synchronized (mLock) {
158 events = mBuffer;
159 dropped = mDropped;
160 initBuffer();
161 }
162
163 final byte[] data;
164 try {
165 data = IpConnectivityEventBuilder.serialize(dropped, events);
166 } catch (IOException e) {
167 Log.e(TAG, "could not serialize events", e);
168 return "";
169 }
170
171 return Base64.encodeToString(data, Base64.DEFAULT);
172 }
173
174 /**
175 * Clears the event buffer and prints its content as a protobuf serialized byte array
176 * inside a base64 encoded string.
177 */
178 private void cmdFlush(FileDescriptor fd, PrintWriter pw, String[] args) {
179 pw.print(flushEncodedOutput());
180 }
181
182 /**
183 * Prints the content of the event buffer, either using the events ASCII representation
184 * or using protobuf text format.
185 */
186 private void cmdList(FileDescriptor fd, PrintWriter pw, String[] args) {
187 final ArrayList<ConnectivityMetricsEvent> events;
188 synchronized (mLock) {
189 events = new ArrayList(mBuffer);
190 }
191
192 if (args.length > 1 && args[1].equals("proto")) {
193 for (IpConnectivityEvent ev : IpConnectivityEventBuilder.toProto(events)) {
194 pw.print(ev.toString());
195 }
196 return;
197 }
198
199 for (ConnectivityMetricsEvent ev : events) {
200 pw.println(ev.toString());
201 }
202 }
203
204 private void cmdStats(FileDescriptor fd, PrintWriter pw, String[] args) {
205 synchronized (mLock) {
206 pw.println("Buffered events: " + mBuffer.size());
207 pw.println("Buffer capacity: " + mCapacity);
208 pw.println("Dropped events: " + mDropped);
209 }
Hugo Benichie69608f2016-09-23 14:48:01 +0900210 if (mNetdListener != null) {
211 mNetdListener.dump(pw);
Hugo Benichi00a42d42016-09-13 15:55:09 +0900212 }
Hugo Benichieab511b2016-09-09 09:23:47 +0900213 }
214
215 private void cmdDefault(FileDescriptor fd, PrintWriter pw, String[] args) {
216 if (args.length == 0) {
217 pw.println("No command");
218 return;
219 }
220 pw.println("Unknown command " + TextUtils.join(" ", args));
221 }
222
223 public final class Impl extends IIpConnectivityMetrics.Stub {
224 static final String CMD_FLUSH = "flush";
225 static final String CMD_LIST = "list";
226 static final String CMD_STATS = "stats";
Hugo Benichi51d14cb2016-10-19 13:48:40 +0900227 static final String CMD_DUMPSYS = "-a"; // dumpsys.cpp dumps services with "-a" as arguments
Hugo Benichieab511b2016-09-09 09:23:47 +0900228 static final String CMD_DEFAULT = CMD_STATS;
229
230 @Override
231 public int logEvent(ConnectivityMetricsEvent event) {
232 enforceConnectivityInternalPermission();
233 return append(event);
234 }
235
236 @Override
237 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
238 enforceDumpPermission();
239 if (DBG) Log.d(TAG, "dumpsys " + TextUtils.join(" ", args));
240 final String cmd = (args.length > 0) ? args[0] : CMD_DEFAULT;
241 switch (cmd) {
242 case CMD_FLUSH:
243 cmdFlush(fd, pw, args);
244 return;
Hugo Benichi51d14cb2016-10-19 13:48:40 +0900245 case CMD_DUMPSYS:
246 // Fallthrough to CMD_LIST when dumpsys.cpp dumps services states (bug reports)
Hugo Benichieab511b2016-09-09 09:23:47 +0900247 case CMD_LIST:
248 cmdList(fd, pw, args);
249 return;
250 case CMD_STATS:
251 cmdStats(fd, pw, args);
252 return;
253 default:
254 cmdDefault(fd, pw, args);
255 }
256 }
257
258 private void enforceConnectivityInternalPermission() {
259 enforcePermission(android.Manifest.permission.CONNECTIVITY_INTERNAL);
260 }
261
262 private void enforceDumpPermission() {
263 enforcePermission(android.Manifest.permission.DUMP);
264 }
265
266 private void enforcePermission(String what) {
267 getContext().enforceCallingOrSelfPermission(what, "IpConnectivityMetrics");
268 }
Michal Karpinskidd9bb4f2016-10-12 14:59:26 +0100269
270 private void enforceNetdEventListeningPermission() {
271 final int uid = Binder.getCallingUid();
272 if (uid != Process.SYSTEM_UID) {
273 throw new SecurityException(String.format("Uid %d has no permission to listen for"
274 + " netd events.", uid));
275 }
276 }
277
278 @Override
279 public boolean registerNetdEventCallback(INetdEventCallback callback) {
280 enforceNetdEventListeningPermission();
281 if (mNetdListener == null) {
282 return false;
283 }
284 return mNetdListener.registerNetdEventCallback(callback);
285 }
286
287 @Override
288 public boolean unregisterNetdEventCallback() {
289 enforceNetdEventListeningPermission();
290 if (mNetdListener == null) {
291 // if the service is null, we aren't registered anyway
292 return true;
293 }
294 return mNetdListener.unregisterNetdEventCallback();
295 }
Hugo Benichieab511b2016-09-09 09:23:47 +0900296 };
Hugo Benichi05686db2016-10-19 11:17:28 +0900297
298 private static final ToIntFunction<Context> READ_BUFFER_SIZE = (ctx) -> {
299 int size = Settings.Global.getInt(ctx.getContentResolver(),
300 Settings.Global.CONNECTIVITY_METRICS_BUFFER_SIZE, DEFAULT_BUFFER_SIZE);
301 if (size <= 0) {
302 return DEFAULT_BUFFER_SIZE;
303 }
304 return Math.min(size, MAXIMUM_BUFFER_SIZE);
305 };
Hugo Benichie1c173d2016-10-18 10:36:33 +0900306
307 private static ArrayMap<Class<?>, TokenBucket> makeRateLimitingBuckets() {
308 ArrayMap<Class<?>, TokenBucket> map = new ArrayMap<>();
309 // one token every minute, 50 tokens max: burst of ~50 events every hour.
310 map.put(ApfProgramEvent.class, new TokenBucket((int)DateUtils.MINUTE_IN_MILLIS, 50));
311 return map;
312 }
Hugo Benichieab511b2016-09-09 09:23:47 +0900313}