|
| 1 | +// Copyright (C) 2026 The Android Open Source Project |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import protos from '../../../protos'; |
| 16 | +import {AdbDevice} from '../../dev.perfetto.RecordTraceV2/adb/adb_device'; |
| 17 | +import {createAdbTracingSession} from '../../dev.perfetto.RecordTraceV2/adb/adb_tracing_session'; |
| 18 | +import {TracingSession} from '../../dev.perfetto.RecordTraceV2/interfaces/tracing_session'; |
| 19 | +import {TracedWebsocketTarget} from '../../dev.perfetto.RecordTraceV2/traced_over_websocket/traced_websocket_target'; |
| 20 | + |
| 21 | +const DUMP_INTERVAL_MS = 10_000; |
| 22 | +const PROC_STATS_BUFFER_SIZE_KB = 4 * 1024; |
| 23 | +const HEAPPROFD_BUFFER_SIZE_KB = 128 * 1024; |
| 24 | +const JAVA_HPROF_BUFFER_SIZE_KB = 256 * 1024; |
| 25 | +const STATS_POLL_INTERVAL_MS = 3000; |
| 26 | + |
| 27 | +export type ProfileState = 'recording' | 'stopping' | 'finished' | 'error'; |
| 28 | + |
| 29 | +export class ProfileSession { |
| 30 | + readonly pid: number; |
| 31 | + readonly processName: string; |
| 32 | + readonly startX: number; |
| 33 | + |
| 34 | + private inner?: TracingSession; |
| 35 | + private intervalHandle?: ReturnType<typeof setInterval>; |
| 36 | + private _state: ProfileState = 'recording'; |
| 37 | + private _error?: string; |
| 38 | + private _bufferUsagePct?: number; |
| 39 | + |
| 40 | + private constructor(pid: number, processName: string, startX: number) { |
| 41 | + this.pid = pid; |
| 42 | + this.processName = processName; |
| 43 | + this.startX = startX; |
| 44 | + } |
| 45 | + |
| 46 | + static async start( |
| 47 | + targetOrDevice: TracedWebsocketTarget | AdbDevice, |
| 48 | + pid: number, |
| 49 | + processName: string, |
| 50 | + startX: number, |
| 51 | + ): Promise<ProfileSession> { |
| 52 | + const self = new ProfileSession(pid, processName, startX); |
| 53 | + const config = buildProcessProfileConfig(pid); |
| 54 | + const result = |
| 55 | + targetOrDevice instanceof TracedWebsocketTarget |
| 56 | + ? await targetOrDevice.startTracing(config) |
| 57 | + : await createAdbTracingSession(targetOrDevice, config); |
| 58 | + if (!result.ok) { |
| 59 | + self._state = 'error'; |
| 60 | + self._error = `Failed to start profile: ${result.error}`; |
| 61 | + return self; |
| 62 | + } |
| 63 | + self.inner = result.value; |
| 64 | + self.intervalHandle = setInterval(async () => { |
| 65 | + self._bufferUsagePct = await self.inner!.getBufferUsagePct(); |
| 66 | + }, STATS_POLL_INTERVAL_MS); |
| 67 | + self.inner.onSessionUpdate.addListener(() => { |
| 68 | + const s = self.inner!.state; |
| 69 | + if (s === 'FINISHED') { |
| 70 | + self._state = 'finished'; |
| 71 | + } else if (s === 'ERRORED') { |
| 72 | + self._state = 'error'; |
| 73 | + self._error = self |
| 74 | + .inner!.logs.filter((l) => l.isError) |
| 75 | + .map((l) => l.message) |
| 76 | + .join('; '); |
| 77 | + } |
| 78 | + }); |
| 79 | + return self; |
| 80 | + } |
| 81 | + |
| 82 | + get state(): ProfileState { |
| 83 | + return this._state; |
| 84 | + } |
| 85 | + |
| 86 | + get error(): string | undefined { |
| 87 | + return this._error; |
| 88 | + } |
| 89 | + |
| 90 | + get bufferUsagePct(): number | undefined { |
| 91 | + return this._bufferUsagePct; |
| 92 | + } |
| 93 | + |
| 94 | + /** Stops recording and waits for the trace data to be ready. */ |
| 95 | + async stop(): Promise<void> { |
| 96 | + if (this._state !== 'recording' || this.inner === undefined) return; |
| 97 | + clearInterval(this.intervalHandle); |
| 98 | + this._state = 'stopping'; |
| 99 | + await this.inner.stop(); |
| 100 | + if (this.inner.state !== 'FINISHED') { |
| 101 | + await new Promise<void>((resolve) => { |
| 102 | + const sub = this.inner!.onSessionUpdate.addListener(() => { |
| 103 | + const s = this.inner!.state; |
| 104 | + if (s === 'FINISHED' || s === 'ERRORED') { |
| 105 | + sub[Symbol.dispose](); |
| 106 | + resolve(); |
| 107 | + } |
| 108 | + }); |
| 109 | + }); |
| 110 | + } |
| 111 | + this._state = this.inner.state === 'FINISHED' ? 'finished' : 'error'; |
| 112 | + } |
| 113 | + |
| 114 | + /** Cancels recording and discards trace data. */ |
| 115 | + async cancel(): Promise<void> { |
| 116 | + if (this._state !== 'recording' || this.inner === undefined) return; |
| 117 | + clearInterval(this.intervalHandle); |
| 118 | + this._state = 'error'; |
| 119 | + await this.inner.cancel(); |
| 120 | + } |
| 121 | + |
| 122 | + /** Returns the trace buffer once state is 'finished'. */ |
| 123 | + getTraceData(): Uint8Array | undefined { |
| 124 | + return this.inner?.getTraceData(); |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +function buildProcessProfileConfig(pid: number): protos.ITraceConfig { |
| 129 | + return { |
| 130 | + compressionType: |
| 131 | + protos.TraceConfig.CompressionType.COMPRESSION_TYPE_DEFLATE, |
| 132 | + buffers: [ |
| 133 | + { |
| 134 | + name: 'process_stats', |
| 135 | + sizeKb: PROC_STATS_BUFFER_SIZE_KB, |
| 136 | + fillPolicy: protos.TraceConfig.BufferConfig.FillPolicy.DISCARD, |
| 137 | + }, |
| 138 | + { |
| 139 | + name: 'heapprofd', |
| 140 | + sizeKb: HEAPPROFD_BUFFER_SIZE_KB, |
| 141 | + fillPolicy: protos.TraceConfig.BufferConfig.FillPolicy.RING_BUFFER, |
| 142 | + }, |
| 143 | + { |
| 144 | + name: 'java_hprof', |
| 145 | + sizeKb: JAVA_HPROF_BUFFER_SIZE_KB, |
| 146 | + fillPolicy: protos.TraceConfig.BufferConfig.FillPolicy.RING_BUFFER, |
| 147 | + }, |
| 148 | + ], |
| 149 | + dataSources: [ |
| 150 | + { |
| 151 | + config: { |
| 152 | + name: 'linux.process_stats', |
| 153 | + targetBufferName: 'process_stats', |
| 154 | + processStatsConfig: { |
| 155 | + scanAllProcessesOnStart: true, // Necessary for track names. |
| 156 | + }, |
| 157 | + }, |
| 158 | + }, |
| 159 | + { |
| 160 | + config: { |
| 161 | + name: 'android.heapprofd', |
| 162 | + targetBufferName: 'heapprofd', |
| 163 | + heapprofdConfig: { |
| 164 | + pid: [pid], |
| 165 | + samplingIntervalBytes: 32 * 1024, // Slightly larger than default to reduce overhead. |
| 166 | + shmemSizeBytes: 16 * 1024 * 1024, // Arbitrary, could use default. |
| 167 | + blockClient: true, // Important for trace integrity. |
| 168 | + continuousDumpConfig: { |
| 169 | + dumpIntervalMs: DUMP_INTERVAL_MS, // Important for getting regular heap snapshots to see how memory usage evolves over time. |
| 170 | + }, |
| 171 | + }, |
| 172 | + }, |
| 173 | + }, |
| 174 | + { |
| 175 | + config: { |
| 176 | + name: 'android.java_hprof', |
| 177 | + targetBufferName: 'java_hprof', |
| 178 | + javaHprofConfig: { |
| 179 | + pid: [pid], |
| 180 | + continuousDumpConfig: { |
| 181 | + dumpIntervalMs: DUMP_INTERVAL_MS, // Required for Java profiles. |
| 182 | + }, |
| 183 | + }, |
| 184 | + }, |
| 185 | + }, |
| 186 | + ], |
| 187 | + }; |
| 188 | +} |
0 commit comments