DropBoxManager.java revision b247536aa3d458750edbc6b45b2348a994d83426
1/*
2 * Copyright (C) 2009 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 android.os;
18
19import android.util.Log;
20
21import com.android.internal.os.IDropBoxManagerService;
22
23import java.io.ByteArrayInputStream;
24import java.io.File;
25import java.io.FileInputStream;
26import java.io.IOException;
27import java.io.InputStream;
28import java.util.zip.GZIPInputStream;
29
30/**
31 * Enqueues chunks of data (from various sources -- application crashes, kernel
32 * log records, etc.).  The queue is size bounded and will drop old data if the
33 * enqueued data exceeds the maximum size.  You can think of this as a
34 * persistent, system-wide, blob-oriented "logcat".
35 *
36 * <p>You can obtain an instance of this class by calling
37 * {@link android.content.Context#getSystemService}
38 * with {@link android.content.Context#DROPBOX_SERVICE}.
39 *
40 * <p>DropBoxManager entries are not sent anywhere directly, but other system
41 * services and debugging tools may scan and upload entries for processing.
42 */
43public class DropBoxManager {
44    private static final String TAG = "DropBoxManager";
45    private final IDropBoxManagerService mService;
46
47    /** Flag value: Entry's content was deleted to save space. */
48    public static final int IS_EMPTY = 1;
49
50    /** Flag value: Content is human-readable UTF-8 text (can be combined with IS_GZIPPED). */
51    public static final int IS_TEXT = 2;
52
53    /** Flag value: Content can be decompressed with {@link java.util.zip.GZIPOutputStream}. */
54    public static final int IS_GZIPPED = 4;
55
56    /**
57     * Broadcast Action: This is broadcast when a new entry is added in the dropbox.
58     * You must hold the {@link android.Manifest.permission#READ_LOGS} permission
59     * in order to receive this broadcast.
60     *
61     * <p class="note">This is a protected intent that can only be sent
62     * by the system.
63     */
64    public static final String ACTION_DROPBOX_ENTRY_ADDED =
65        "android.intent.action.DROPBOX_ENTRY_ADDED";
66
67    /**
68     * Extra for {@link android.os.DropBoxManager#ACTION_DROPBOX_ENTRY_ADDED}:
69     * string containing the dropbox tag.
70     */
71    public static final String EXTRA_TAG = "tag";
72
73    /**
74     * Extra for {@link android.os.DropBoxManager#ACTION_DROPBOX_ENTRY_ADDED}:
75     * long integer value containing time (in milliseconds since January 1, 1970 00:00:00 UTC)
76     * when the entry was created.
77     */
78    public static final String EXTRA_TIME = "time";
79
80    /**
81     * A single entry retrieved from the drop box.
82     * This may include a reference to a stream, so you must call
83     * {@link #close()} when you are done using it.
84     */
85    public static class Entry implements Parcelable {
86        private final String mTag;
87        private final long mTimeMillis;
88
89        private final byte[] mData;
90        private final ParcelFileDescriptor mFileDescriptor;
91        private final int mFlags;
92
93        /** Create a new empty Entry with no contents. */
94        public Entry(String tag, long millis) {
95            this(tag, millis, (Object) null, IS_EMPTY);
96        }
97
98        /** Create a new Entry with plain text contents. */
99        public Entry(String tag, long millis, String text) {
100            this(tag, millis, (Object) text.getBytes(), IS_TEXT);
101        }
102
103        /**
104         * Create a new Entry with byte array contents.
105         * The data array must not be modified after creating this entry.
106         */
107        public Entry(String tag, long millis, byte[] data, int flags) {
108            this(tag, millis, (Object) data, flags);
109        }
110
111        /**
112         * Create a new Entry with streaming data contents.
113         * Takes ownership of the ParcelFileDescriptor.
114         */
115        public Entry(String tag, long millis, ParcelFileDescriptor data, int flags) {
116            this(tag, millis, (Object) data, flags);
117        }
118
119        /**
120         * Create a new Entry with the contents read from a file.
121         * The file will be read when the entry's contents are requested.
122         */
123        public Entry(String tag, long millis, File data, int flags) throws IOException {
124            this(tag, millis, (Object) ParcelFileDescriptor.open(
125                    data, ParcelFileDescriptor.MODE_READ_ONLY), flags);
126        }
127
128        /** Internal constructor for CREATOR.createFromParcel(). */
129        private Entry(String tag, long millis, Object value, int flags) {
130            if (tag == null) throw new NullPointerException();
131            if (((flags & IS_EMPTY) != 0) != (value == null)) throw new IllegalArgumentException();
132
133            mTag = tag;
134            mTimeMillis = millis;
135            mFlags = flags;
136
137            if (value == null) {
138                mData = null;
139                mFileDescriptor = null;
140            } else if (value instanceof byte[]) {
141                mData = (byte[]) value;
142                mFileDescriptor = null;
143            } else if (value instanceof ParcelFileDescriptor) {
144                mData = null;
145                mFileDescriptor = (ParcelFileDescriptor) value;
146            } else {
147                throw new IllegalArgumentException();
148            }
149        }
150
151        /** Close the input stream associated with this entry. */
152        public void close() {
153            try { if (mFileDescriptor != null) mFileDescriptor.close(); } catch (IOException e) { }
154        }
155
156        /** @return the tag originally attached to the entry. */
157        public String getTag() { return mTag; }
158
159        /** @return time when the entry was originally created. */
160        public long getTimeMillis() { return mTimeMillis; }
161
162        /** @return flags describing the content returned by @{link #getInputStream()}. */
163        public int getFlags() { return mFlags & ~IS_GZIPPED; }  // getInputStream() decompresses.
164
165        /**
166         * @param maxBytes of string to return (will truncate at this length).
167         * @return the uncompressed text contents of the entry, null if the entry is not text.
168         */
169        public String getText(int maxBytes) {
170            if ((mFlags & IS_TEXT) == 0) return null;
171            if (mData != null) return new String(mData, 0, Math.min(maxBytes, mData.length));
172
173            InputStream is = null;
174            try {
175                is = getInputStream();
176                byte[] buf = new byte[maxBytes];
177                int readBytes = 0;
178                int n = 0;
179                while (n >= 0 && (readBytes += n) < maxBytes) {
180                    n = is.read(buf, readBytes, maxBytes - readBytes);
181                }
182                return new String(buf, 0, readBytes);
183            } catch (IOException e) {
184                return null;
185            } finally {
186                try { if (is != null) is.close(); } catch (IOException e) {}
187            }
188        }
189
190        /** @return the uncompressed contents of the entry, or null if the contents were lost */
191        public InputStream getInputStream() throws IOException {
192            InputStream is;
193            if (mData != null) {
194                is = new ByteArrayInputStream(mData);
195            } else if (mFileDescriptor != null) {
196                is = new ParcelFileDescriptor.AutoCloseInputStream(mFileDescriptor);
197            } else {
198                return null;
199            }
200            return (mFlags & IS_GZIPPED) != 0 ? new GZIPInputStream(is) : is;
201        }
202
203        public static final Parcelable.Creator<Entry> CREATOR = new Parcelable.Creator() {
204            public Entry[] newArray(int size) { return new Entry[size]; }
205            public Entry createFromParcel(Parcel in) {
206                return new Entry(
207                        in.readString(), in.readLong(), in.readValue(null), in.readInt());
208            }
209        };
210
211        public int describeContents() {
212            return mFileDescriptor != null ? Parcelable.CONTENTS_FILE_DESCRIPTOR : 0;
213        }
214
215        public void writeToParcel(Parcel out, int flags) {
216            out.writeString(mTag);
217            out.writeLong(mTimeMillis);
218            if (mFileDescriptor != null) {
219                out.writeValue(mFileDescriptor);
220            } else {
221                out.writeValue(mData);
222            }
223            out.writeInt(mFlags);
224        }
225    }
226
227    /** {@hide} */
228    public DropBoxManager(IDropBoxManagerService service) { mService = service; }
229
230    /**
231     * Create a dummy instance for testing.  All methods will fail unless
232     * overridden with an appropriate mock implementation.  To obtain a
233     * functional instance, use {@link android.content.Context#getSystemService}.
234     */
235    protected DropBoxManager() { mService = null; }
236
237    /**
238     * Stores human-readable text.  The data may be discarded eventually (or even
239     * immediately) if space is limited, or ignored entirely if the tag has been
240     * blocked (see {@link #isTagEnabled}).
241     *
242     * @param tag describing the type of entry being stored
243     * @param data value to store
244     */
245    public void addText(String tag, String data) {
246        try { mService.add(new Entry(tag, 0, data)); } catch (RemoteException e) {}
247    }
248
249    /**
250     * Stores binary data, which may be ignored or discarded as with {@link #addText}.
251     *
252     * @param tag describing the type of entry being stored
253     * @param data value to store
254     * @param flags describing the data
255     */
256    public void addData(String tag, byte[] data, int flags) {
257        if (data == null) throw new NullPointerException();
258        try { mService.add(new Entry(tag, 0, data, flags)); } catch (RemoteException e) {}
259    }
260
261    /**
262     * Stores the contents of a file, which may be ignored or discarded as with
263     * {@link #addText}.
264     *
265     * @param tag describing the type of entry being stored
266     * @param file to read from
267     * @param flags describing the data
268     * @throws IOException if the file can't be opened
269     */
270    public void addFile(String tag, File file, int flags) throws IOException {
271        if (file == null) throw new NullPointerException();
272        Entry entry = new Entry(tag, 0, file, flags);
273        try {
274            mService.add(new Entry(tag, 0, file, flags));
275        } catch (RemoteException e) {
276            // ignore
277        } finally {
278            entry.close();
279        }
280    }
281
282    /**
283     * Checks any blacklists (set in system settings) to see whether a certain
284     * tag is allowed.  Entries with disabled tags will be dropped immediately,
285     * so you can save the work of actually constructing and sending the data.
286     *
287     * @param tag that would be used in {@link #addText} or {@link #addFile}
288     * @return whether events with that tag would be accepted
289     */
290    public boolean isTagEnabled(String tag) {
291        try { return mService.isTagEnabled(tag); } catch (RemoteException e) { return false; }
292    }
293
294    /**
295     * Gets the next entry from the drop box *after* the specified time.
296     * Requires android.permission.READ_LOGS.  You must always call
297     * {@link Entry#close()} on the return value!
298     *
299     * @param tag of entry to look for, null for all tags
300     * @param msec time of the last entry seen
301     * @return the next entry, or null if there are no more entries
302     */
303    public Entry getNextEntry(String tag, long msec) {
304        try { return mService.getNextEntry(tag, msec); } catch (RemoteException e) { return null; }
305    }
306
307    // TODO: It may be useful to have some sort of notification mechanism
308    // when data is added to the dropbox, for demand-driven readers --
309    // for now readers need to poll the dropbox to find new data.
310}
311