2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server.connectivity;
19 import com.android.server.SystemService;
21 import android.app.PendingIntent;
22 import android.content.Context;
23 import android.content.pm.PackageManager;
24 import android.net.ConnectivityMetricsEvent;
25 import android.net.ConnectivityMetricsLogger;
26 import android.net.IConnectivityMetricsLogger;
27 import android.os.Binder;
28 import android.os.Parcel;
29 import android.text.format.DateUtils;
30 import android.util.Log;
32 import java.io.FileDescriptor;
33 import java.io.PrintWriter;
34 import java.util.ArrayDeque;
35 import java.util.ArrayList;
38 public class MetricsLoggerService extends SystemService {
39 private static String TAG = "ConnectivityMetricsLoggerService";
40 private static final boolean DBG = true;
41 private static final boolean VDBG = false;
43 public MetricsLoggerService(Context context) {
48 public void onStart() {
49 resetThrottlingCounters(System.currentTimeMillis());
53 public void onBootPhase(int phase) {
54 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
55 if (DBG) Log.d(TAG, "onBootPhase: PHASE_SYSTEM_SERVICES_READY");
56 publishBinderService(ConnectivityMetricsLogger.CONNECTIVITY_METRICS_LOGGER_SERVICE,
58 mDnsListener = new DnsEventListenerService(getContext());
59 publishBinderService(mDnsListener.SERVICE_NAME, mDnsListener);
63 // TODO: read from system property
64 private final int MAX_NUMBER_OF_EVENTS = 1000;
66 // TODO: read from system property
67 private final int EVENTS_NOTIFICATION_THRESHOLD = 300;
69 // TODO: read from system property
70 private final int THROTTLING_TIME_INTERVAL_MILLIS = 60 * 60 * 1000; // 1 hour
72 // TODO: read from system property
73 private final int THROTTLING_MAX_NUMBER_OF_MESSAGES_PER_COMPONENT = 1000;
75 private int mEventCounter = 0;
78 * Reference of the last event in the list of cached events.
80 * When client of this service retrieves events by calling getEvents, it is passing
81 * ConnectivityMetricsEvent.Reference object. After getEvents returns, that object will
82 * contain this reference. The client can save it and use next time it calls getEvents.
83 * This way only new events will be returned.
85 private long mLastEventReference = 0;
87 private final int mThrottlingCounters[] =
88 new int[ConnectivityMetricsLogger.NUMBER_OF_COMPONENTS];
90 private long mThrottlingIntervalBoundaryMillis;
92 private final ArrayDeque<ConnectivityMetricsEvent> mEvents = new ArrayDeque<>();
94 private DnsEventListenerService mDnsListener;
96 private void enforceConnectivityInternalPermission() {
97 getContext().enforceCallingOrSelfPermission(
98 android.Manifest.permission.CONNECTIVITY_INTERNAL,
99 "MetricsLoggerService");
102 private void enforceDumpPermission() {
103 getContext().enforceCallingOrSelfPermission(
104 android.Manifest.permission.DUMP,
105 "MetricsLoggerService");
108 private void resetThrottlingCounters(long currentTimeMillis) {
109 synchronized (mThrottlingCounters) {
110 for (int i = 0; i < mThrottlingCounters.length; i++) {
111 mThrottlingCounters[i] = 0;
113 mThrottlingIntervalBoundaryMillis =
114 currentTimeMillis + THROTTLING_TIME_INTERVAL_MILLIS;
118 private void addEvent(ConnectivityMetricsEvent e) {
120 Log.v(TAG, "writeEvent(" + e.toString() + ")");
123 while (mEvents.size() >= MAX_NUMBER_OF_EVENTS) {
124 mEvents.removeFirst();
131 * Implementation of the IConnectivityMetricsLogger interface.
133 private final IConnectivityMetricsLogger.Stub mBinder = new IConnectivityMetricsLogger.Stub() {
135 private final ArrayList<PendingIntent> mPendingIntents = new ArrayList<>();
138 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
139 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
140 != PackageManager.PERMISSION_GRANTED) {
141 pw.println("Permission Denial: can't dump ConnectivityMetricsLoggerService " +
142 "from from pid=" + Binder.getCallingPid() + ", uid=" +
143 Binder.getCallingUid());
147 boolean dumpSerializedSize = false;
148 boolean dumpEvents = false;
149 boolean dumpDebugInfo = false;
150 for (String arg : args) {
153 dumpDebugInfo = true;
161 dumpSerializedSize = true;
165 dumpDebugInfo = true;
167 dumpSerializedSize = true;
172 synchronized (mEvents) {
173 pw.println("Number of events: " + mEvents.size());
174 pw.println("Counter: " + mEventCounter);
175 if (mEvents.size() > 0) {
176 pw.println("Time span: " +
177 DateUtils.formatElapsedTime(
178 (System.currentTimeMillis() - mEvents.peekFirst().timestamp)
182 if (dumpSerializedSize) {
183 Parcel p = Parcel.obtain();
184 for (ConnectivityMetricsEvent e : mEvents) {
185 p.writeParcelable(e, 0);
187 pw.println("Serialized data size: " + p.dataSize());
193 pw.println("Events:");
194 for (ConnectivityMetricsEvent e : mEvents) {
195 pw.println(e.toString());
201 synchronized (mThrottlingCounters) {
203 for (int i = 0; i < ConnectivityMetricsLogger.NUMBER_OF_COMPONENTS; i++) {
204 if (mThrottlingCounters[i] > 0) {
205 pw.println("Throttling Counter #" + i + ": " + mThrottlingCounters[i]);
208 pw.println("Throttling Time Remaining: " +
209 DateUtils.formatElapsedTime(
210 (mThrottlingIntervalBoundaryMillis - System.currentTimeMillis())
215 synchronized (mPendingIntents) {
216 if (!mPendingIntents.isEmpty()) {
218 pw.println("Pending intents:");
219 for (PendingIntent pi : mPendingIntents) {
220 pw.println(pi.toString());
226 mDnsListener.dump(pw);
229 public long logEvent(ConnectivityMetricsEvent event) {
230 ConnectivityMetricsEvent[] events = new ConnectivityMetricsEvent[]{event};
231 return logEvents(events);
237 * Note: All events must belong to the same component.
239 * @return 0 on success
240 * <0 if error happened
241 * >0 timestamp after which new events will be accepted
243 public long logEvents(ConnectivityMetricsEvent[] events) {
244 enforceConnectivityInternalPermission();
246 if (events == null || events.length == 0) {
247 Log.wtf(TAG, "No events passed to logEvents()");
251 int componentTag = events[0].componentTag;
252 if (componentTag < 0 ||
253 componentTag >= ConnectivityMetricsLogger.NUMBER_OF_COMPONENTS) {
254 Log.wtf(TAG, "Unexpected tag: " + componentTag);
258 synchronized (mThrottlingCounters) {
259 long currentTimeMillis = System.currentTimeMillis();
260 if (currentTimeMillis > mThrottlingIntervalBoundaryMillis) {
261 resetThrottlingCounters(currentTimeMillis);
264 mThrottlingCounters[componentTag] += events.length;
266 if (mThrottlingCounters[componentTag] >
267 THROTTLING_MAX_NUMBER_OF_MESSAGES_PER_COMPONENT) {
268 Log.w(TAG, "Too many events from #" + componentTag +
269 ". Block until " + mThrottlingIntervalBoundaryMillis);
271 return mThrottlingIntervalBoundaryMillis;
275 boolean sendPendingIntents = false;
277 synchronized (mEvents) {
278 for (ConnectivityMetricsEvent e : events) {
279 if (e.componentTag != componentTag) {
280 Log.wtf(TAG, "Unexpected tag: " + e.componentTag);
287 mLastEventReference += events.length;
289 mEventCounter += events.length;
290 if (mEventCounter >= EVENTS_NOTIFICATION_THRESHOLD) {
292 sendPendingIntents = true;
296 if (sendPendingIntents) {
297 synchronized (mPendingIntents) {
298 for (PendingIntent pi : mPendingIntents) {
299 if (VDBG) Log.v(TAG, "Send pending intent");
301 pi.send(getContext(), 0, null, null, null);
302 } catch (PendingIntent.CanceledException e) {
303 Log.e(TAG, "Pending intent canceled: " + pi);
304 mPendingIntents.remove(pi);
316 * @param reference of the last event previously returned. The function will return
317 * events following it.
318 * If 0 then all events will be returned.
319 * After the function call it will contain reference of the
320 * last returned event.
323 public ConnectivityMetricsEvent[] getEvents(ConnectivityMetricsEvent.Reference reference) {
324 enforceDumpPermission();
325 long ref = reference.getValue();
326 if (VDBG) Log.v(TAG, "getEvents(" + ref + ")");
328 ConnectivityMetricsEvent[] result;
329 synchronized (mEvents) {
330 if (ref > mLastEventReference) {
331 Log.e(TAG, "Invalid reference");
332 reference.setValue(mLastEventReference);
335 if (ref < mLastEventReference - mEvents.size()) {
336 ref = mLastEventReference - mEvents.size();
339 int numEventsToSkip =
340 mEvents.size() // Total number of events
341 - (int)(mLastEventReference - ref); // Number of events to return
343 result = new ConnectivityMetricsEvent[mEvents.size() - numEventsToSkip];
345 for (ConnectivityMetricsEvent e : mEvents) {
346 if (numEventsToSkip > 0) {
353 reference.setValue(mLastEventReference);
359 public boolean register(PendingIntent newEventsIntent) {
360 enforceDumpPermission();
361 if (VDBG) Log.v(TAG, "register(" + newEventsIntent + ")");
363 synchronized (mPendingIntents) {
364 if (mPendingIntents.remove(newEventsIntent)) {
365 Log.w(TAG, "Replacing registered pending intent");
367 mPendingIntents.add(newEventsIntent);
373 public void unregister(PendingIntent newEventsIntent) {
374 enforceDumpPermission();
375 if (VDBG) Log.v(TAG, "unregister(" + newEventsIntent + ")");
377 synchronized (mPendingIntents) {
378 if (!mPendingIntents.remove(newEventsIntent)) {
379 Log.e(TAG, "Pending intent is not registered");