1 /* 2 * Copyright (C) 2018 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 17 #ifndef SRC_PERFETTO_CMD_PERFETTO_CMD_H_ 18 #define SRC_PERFETTO_CMD_PERFETTO_CMD_H_ 19 20 #include <cstdint> 21 #include <functional> 22 #include <list> 23 #include <memory> 24 #include <optional> 25 #include <string> 26 #include <vector> 27 28 #include "perfetto/base/build_config.h" 29 #include "perfetto/ext/base/event_fd.h" 30 #include "perfetto/ext/base/pipe.h" 31 #include "perfetto/ext/base/scoped_file.h" 32 #include "perfetto/ext/base/thread_task_runner.h" 33 #include "perfetto/ext/base/unix_task_runner.h" 34 #include "perfetto/ext/base/uuid.h" 35 #include "perfetto/ext/base/weak_ptr.h" 36 #include "perfetto/ext/tracing/core/basic_types.h" 37 #include "perfetto/ext/tracing/core/consumer.h" 38 #include "perfetto/ext/tracing/ipc/consumer_ipc_client.h" 39 #include "perfetto/tracing/core/forward_decls.h" 40 #include "src/android_stats/perfetto_atoms.h" 41 #include "src/perfetto_cmd/packet_writer.h" 42 43 namespace perfetto { 44 45 class RateLimiter; 46 47 // Directory for local state and temporary files. This is automatically 48 // created by the system by setting setprop persist.traced.enable=1. 49 extern const char* kStateDir; 50 51 class PerfettoCmd : public Consumer { 52 public: 53 PerfettoCmd(); 54 ~PerfettoCmd() override; 55 56 // The main() is split in two stages: cmdline parsing and actual interaction 57 // with traced. This is to allow tools like tracebox to avoid spawning the 58 // service for no reason if the cmdline parsing fails. 59 // Return value: 60 // std::nullopt: no error, the caller should call 61 // ConnectToServiceRunAndMaybeNotify. 62 // 0-N: the caller should exit() with the given exit code. 63 std::optional<int> ParseCmdlineAndMaybeDaemonize(int argc, char** argv); 64 int ConnectToServiceRunAndMaybeNotify(); 65 66 // perfetto::Consumer implementation. 67 void OnConnect() override; 68 void OnDisconnect() override; 69 void OnTracingDisabled(const std::string& error) override; 70 void OnTraceData(std::vector<TracePacket>, bool has_more) override; 71 void OnDetach(bool) override; 72 void OnAttach(bool, const TraceConfig&) override; 73 void OnTraceStats(bool, const TraceStats&) override; 74 void OnObservableEvents(const ObservableEvents&) override; 75 void OnSessionCloned(const OnSessionClonedArgs&) override; 76 SignalCtrlC()77 void SignalCtrlC() { ctrl_c_evt_.Notify(); } 78 79 private: 80 enum CloneThreadMode { kSingleExtraThread, kNewThreadPerRequest }; 81 82 bool OpenOutputFile(); 83 void SetupCtrlCSignalHandler(); 84 void FinalizeTraceAndExit(); 85 void PrintUsage(const char* argv0); 86 void PrintServiceState(bool success, const TracingServiceState&); 87 void CloneAllBugreportTraces(bool success, const TracingServiceState&); 88 void CloneSessionOnThread(TracingSessionID, 89 const std::string& cmdline, // \0 separated. 90 CloneThreadMode, 91 std::string clone_trigger_name, 92 std::function<void()> on_clone_callback); 93 void OnTimeout(); is_detach()94 bool is_detach() const { return !detach_key_.empty(); } is_attach()95 bool is_attach() const { return !attach_key_.empty(); } 96 97 // Once we call ReadBuffers we expect one or more calls to OnTraceData 98 // with the last call having |has_more| set to false. However we should 99 // gracefully handle the service failing to ever call OnTraceData or 100 // setting |has_more| incorrectly. To do this we maintain a timeout 101 // which finalizes and exits the client if we don't receive OnTraceData 102 // within OnTraceDataTimeoutMs of when we expected to. 103 void CheckTraceDataTimeout(); 104 105 int ConnectToServiceAndRun(); 106 107 void ReadbackTraceDataAndQuit(const std::string& error); 108 109 enum BgProcessStatus : char { 110 kBackgroundOk = 0, 111 kBackgroundOtherError = 1, 112 kBackgroundTimeout = 2, 113 }; 114 115 // Used to implement the --background-wait flag. 116 // 117 // Waits (up to 30s) for the child process to signal (success or an error). 118 // 119 // Returns the status received from the child process or kTimeout, in case of 120 // timeout. 121 BgProcessStatus WaitOnBgProcessPipe(); 122 123 // Used to implement the --background-wait flag. 124 // 125 // Signals the parent process (if there is one) that it can exit (successfully 126 // or with an error). 127 // 128 // Only the first time this function is called is significant. Further calls 129 // will have no effect. 130 void NotifyBgProcessPipe(BgProcessStatus status); 131 132 void OnCloneSnapshotTriggerReceived(TracingSessionID, 133 std::string trigger_name); 134 135 #if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) 136 static base::ScopedFile CreateUnlinkedTmpFile(); 137 void SaveTraceIntoIncidentOrCrash(); 138 void SaveOutputToIncidentTraceOrCrash(); 139 void ReportTraceToAndroidFrameworkOrCrash(); 140 #endif 141 void LogUploadEvent(PerfettoStatsdAtom atom); 142 void LogUploadEvent(PerfettoStatsdAtom atom, const std::string& trigger_name); 143 void LogTriggerEvents(PerfettoTriggerAtom atom, 144 const std::vector<std::string>& trigger_names); 145 146 base::UnixTaskRunner task_runner_; 147 148 std::unique_ptr<RateLimiter> limiter_; 149 std::unique_ptr<perfetto::TracingService::ConsumerEndpoint> 150 consumer_endpoint_; 151 std::unique_ptr<TraceConfig> trace_config_; 152 std::optional<PacketWriter> packet_writer_; 153 base::ScopedFstream trace_out_stream_; 154 std::vector<std::string> triggers_to_activate_; 155 std::string trace_out_path_; 156 base::EventFd ctrl_c_evt_; 157 bool ctrl_c_handler_installed_ = false; 158 base::Pipe background_wait_pipe_; 159 bool save_to_incidentd_ = false; 160 bool report_to_android_framework_ = false; 161 bool statsd_logging_ = false; 162 bool tracing_succeeded_ = false; 163 uint64_t bytes_written_ = 0; 164 std::string detach_key_; 165 std::string attach_key_; 166 bool stop_trace_once_attached_ = false; 167 bool redetach_once_attached_ = false; 168 bool query_service_ = false; 169 bool query_service_output_raw_ = false; 170 bool query_service_long_ = false; 171 bool clone_all_bugreport_traces_ = false; 172 bool bugreport_ = false; 173 bool background_ = false; 174 bool background_wait_ = false; 175 bool ignore_guardrails_ = false; 176 bool upload_flag_ = false; 177 bool connected_ = false; 178 std::string uuid_; 179 std::optional<TracingSessionID> clone_tsid_{}; 180 bool clone_for_bugreport_ = false; 181 std::function<void()> on_session_cloned_; 182 183 // How long we expect to trace for or 0 if the trace is indefinite. 184 uint32_t expected_duration_ms_ = 0; 185 bool trace_data_timeout_armed_ = false; 186 187 // The aux threads used to invoke secondary instances of PerfettoCmd to create 188 // snapshots. This is used only when the trace config involves a 189 // CLONE_SNAPSHOT trigger or when using --save-all-for-bugreport. 190 std::list<base::ThreadTaskRunner> snapshot_threads_; 191 int snapshot_count_ = 0; 192 std::string snapshot_config_; 193 std::string snapshot_trigger_name_; 194 195 base::WeakPtrFactory<PerfettoCmd> weak_factory_{this}; 196 }; 197 198 } // namespace perfetto 199 200 #endif // SRC_PERFETTO_CMD_PERFETTO_CMD_H_ 201