DropBoxManager.java revision 3685db7f5dd8a830a4e096404d4924e12697fb78
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    /** Flag value for serialization only: Value is a byte array, not a file descriptor */
57    private static final int HAS_BYTE_ARRAY = 8;
58
59    /**
60     * A single entry retrieved from the drop box.
61     * This may include a reference to a stream, so you must call
62     * {@link #close()} when you are done using it.
63     */
64    public static class Entry implements Parcelable {
65        private final String mTag;
66        private final long mTimeMillis;
67
68        private final byte[] mData;
69        private final ParcelFileDescriptor mFileDescriptor;
70        private final int mFlags;
71
72        /** Create a new empty Entry with no contents. */
73        public Entry(String tag, long millis) {
74            if (tag == null) throw new NullPointerException("tag == null");
75
76            mTag = tag;
77            mTimeMillis = millis;
78            mData = null;
79            mFileDescriptor = null;
80            mFlags = IS_EMPTY;
81        }
82
83        /** Create a new Entry with plain text contents. */
84        public Entry(String tag, long millis, String text) {
85            if (tag == null) throw new NullPointerException("tag == null");
86            if (text == null) throw new NullPointerException("text == null");
87
88            mTag = tag;
89            mTimeMillis = millis;
90            mData = text.getBytes();
91            mFileDescriptor = null;
92            mFlags = IS_TEXT;
93        }
94
95        /**
96         * Create a new Entry with byte array contents.
97         * The data array must not be modified after creating this entry.
98         */
99        public Entry(String tag, long millis, byte[] data, int flags) {
100            if (tag == null) throw new NullPointerException("tag == null");
101            if (((flags & IS_EMPTY) != 0) != (data == null)) {
102                throw new IllegalArgumentException("Bad flags: " + flags);
103            }
104
105            mTag = tag;
106            mTimeMillis = millis;
107            mData = data;
108            mFileDescriptor = null;
109            mFlags = flags;
110        }
111
112        /**
113         * Create a new Entry with streaming data contents.
114         * Takes ownership of the ParcelFileDescriptor.
115         */
116        public Entry(String tag, long millis, ParcelFileDescriptor data, int flags) {
117            if (tag == null) throw new NullPointerException("tag == null");
118            if (((flags & IS_EMPTY) != 0) != (data == null)) {
119                throw new IllegalArgumentException("Bad flags: " + flags);
120            }
121
122            mTag = tag;
123            mTimeMillis = millis;
124            mData = null;
125            mFileDescriptor = data;
126            mFlags = flags;
127        }
128
129        /**
130         * Create a new Entry with the contents read from a file.
131         * The file will be read when the entry's contents are requested.
132         */
133        public Entry(String tag, long millis, File data, int flags) throws IOException {
134            if (tag == null) throw new NullPointerException("tag == null");
135            if ((flags & IS_EMPTY) != 0) throw new IllegalArgumentException("Bad flags: " + flags);
136
137            mTag = tag;
138            mTimeMillis = millis;
139            mData = null;
140            mFileDescriptor = ParcelFileDescriptor.open(data, ParcelFileDescriptor.MODE_READ_ONLY);
141            mFlags = flags;
142        }
143
144        /** Close the input stream associated with this entry. */
145        public void close() {
146            try { if (mFileDescriptor != null) mFileDescriptor.close(); } catch (IOException e) { }
147        }
148
149        /** @return the tag originally attached to the entry. */
150        public String getTag() { return mTag; }
151
152        /** @return time when the entry was originally created. */
153        public long getTimeMillis() { return mTimeMillis; }
154
155        /** @return flags describing the content returned by @{link #getInputStream()}. */
156        public int getFlags() { return mFlags & ~IS_GZIPPED; }  // getInputStream() decompresses.
157
158        /**
159         * @param maxBytes of string to return (will truncate at this length).
160         * @return the uncompressed text contents of the entry, null if the entry is not text.
161         */
162        public String getText(int maxBytes) {
163            if ((mFlags & IS_TEXT) == 0) return null;
164            if (mData != null) return new String(mData, 0, Math.min(maxBytes, mData.length));
165
166            InputStream is = null;
167            try {
168                is = getInputStream();
169                if (is == null) return null;
170                byte[] buf = new byte[maxBytes];
171                return new String(buf, 0, Math.max(0, is.read(buf)));
172            } catch (IOException e) {
173                return null;
174            } finally {
175                try { if (is != null) is.close(); } catch (IOException e) {}
176            }
177        }
178
179        /** @return the uncompressed contents of the entry, or null if the contents were lost */
180        public InputStream getInputStream() throws IOException {
181            InputStream is;
182            if (mData != null) {
183                is = new ByteArrayInputStream(mData);
184            } else if (mFileDescriptor != null) {
185                is = new ParcelFileDescriptor.AutoCloseInputStream(mFileDescriptor);
186            } else {
187                return null;
188            }
189            return (mFlags & IS_GZIPPED) != 0 ? new GZIPInputStream(is) : is;
190        }
191
192        public static final Parcelable.Creator<Entry> CREATOR = new Parcelable.Creator() {
193            public Entry[] newArray(int size) { return new Entry[size]; }
194            public Entry createFromParcel(Parcel in) {
195                String tag = in.readString();
196                long millis = in.readLong();
197                int flags = in.readInt();
198                if ((flags & HAS_BYTE_ARRAY) != 0) {
199                    return new Entry(tag, millis, in.createByteArray(), flags & ~HAS_BYTE_ARRAY);
200                } else {
201                    return new Entry(tag, millis, in.readFileDescriptor(), flags);
202                }
203            }
204        };
205
206        public int describeContents() {
207            return mFileDescriptor != null ? Parcelable.CONTENTS_FILE_DESCRIPTOR : 0;
208        }
209
210        public void writeToParcel(Parcel out, int flags) {
211            out.writeString(mTag);
212            out.writeLong(mTimeMillis);
213            if (mFileDescriptor != null) {
214                out.writeInt(mFlags & ~HAS_BYTE_ARRAY);  // Clear bit just to be safe
215                mFileDescriptor.writeToParcel(out, flags);
216            } else {
217                out.writeInt(mFlags | HAS_BYTE_ARRAY);
218                out.writeByteArray(mData);
219            }
220        }
221    }
222
223    /** {@hide} */
224    public DropBoxManager(IDropBoxManagerService service) { mService = service; }
225
226    /**
227     * Create a dummy instance for testing.  All methods will fail unless
228     * overridden with an appropriate mock implementation.  To obtain a
229     * functional instance, use {@link android.content.Context#getSystemService}.
230     */
231    protected DropBoxManager() { mService = null; }
232
233    /**
234     * Stores human-readable text.  The data may be discarded eventually (or even
235     * immediately) if space is limited, or ignored entirely if the tag has been
236     * blocked (see {@link #isTagEnabled}).
237     *
238     * @param tag describing the type of entry being stored
239     * @param data value to store
240     */
241    public void addText(String tag, String data) {
242        try { mService.add(new Entry(tag, 0, data)); } catch (RemoteException e) {}
243    }
244
245    /**
246     * Stores binary data, which may be ignored or discarded as with {@link #addText}.
247     *
248     * @param tag describing the type of entry being stored
249     * @param data value to store
250     * @param flags describing the data
251     */
252    public void addData(String tag, byte[] data, int flags) {
253        if (data == null) throw new NullPointerException("data == null");
254        try { mService.add(new Entry(tag, 0, data, flags)); } catch (RemoteException e) {}
255    }
256
257    /**
258     * Stores the contents of a file, which may be ignored or discarded as with
259     * {@link #addText}.
260     *
261     * @param tag describing the type of entry being stored
262     * @param file to read from
263     * @param flags describing the data
264     * @throws IOException if the file can't be opened
265     */
266    public void addFile(String tag, File file, int flags) throws IOException {
267        if (file == null) throw new NullPointerException("file == null");
268        Entry entry = new Entry(tag, 0, file, flags);
269        try {
270            mService.add(entry);
271        } catch (RemoteException e) {
272            // ignore
273        } finally {
274            entry.close();
275        }
276    }
277
278    /**
279     * Checks any blacklists (set in system settings) to see whether a certain
280     * tag is allowed.  Entries with disabled tags will be dropped immediately,
281     * so you can save the work of actually constructing and sending the data.
282     *
283     * @param tag that would be used in {@link #addText} or {@link #addFile}
284     * @return whether events with that tag would be accepted
285     */
286    public boolean isTagEnabled(String tag) {
287        try { return mService.isTagEnabled(tag); } catch (RemoteException e) { return false; }
288    }
289
290    /**
291     * Gets the next entry from the drop box *after* the specified time.
292     * Requires android.permission.READ_LOGS.  You must always call
293     * {@link Entry#close()} on the return value!
294     *
295     * @param tag of entry to look for, null for all tags
296     * @param msec time of the last entry seen
297     * @return the next entry, or null if there are no more entries
298     */
299    public Entry getNextEntry(String tag, long msec) {
300        try { return mService.getNextEntry(tag, msec); } catch (RemoteException e) { return null; }
301    }
302
303    // TODO: It may be useful to have some sort of notification mechanism
304    // when data is added to the dropbox, for demand-driven readers --
305    // for now readers need to poll the dropbox to find new data.
306}
307