File: trace_net_log_observer.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (346 lines) | stat: -rw-r--r-- 13,948 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/log/trace_net_log_observer.h"

#include <stdio.h>

#include <memory>
#include <string>
#include <utility>

#include "base/check.h"
#include "base/json/json_writer.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "net/base/tracing.h"
#include "net/log/net_log_entry.h"
#include "net/log/net_log_event_type.h"
#include "third_party/perfetto/include/perfetto/tracing/track_event.h"

namespace net {

namespace {

// TraceLog category for NetLog events.
constexpr const char kNetLogTracingCategory[] = "netlog";
constexpr const char kSensitiveNetLogTracingCategory[] =
    TRACE_DISABLED_BY_DEFAULT("netlog.sensitive");

class TracedValue : public base::trace_event::ConvertableToTraceFormat {
 public:
  explicit TracedValue(base::Value::Dict value) : value_(std::move(value)) {}
  ~TracedValue() override = default;

 private:
  void AppendAsTraceFormat(std::string* out) const override {
    if (!value_.empty()) {
      std::string tmp;
      base::JSONWriter::Write(value_, &tmp);
      *out += tmp;
    } else {
      *out += "{}";
    }
  }

 private:
  base::Value::Dict value_;
};

// Inspired by http://crbug.com/418158806#comment2. This is more efficient than
// using TrackEvent::SetTrackDescriptor() because that would require us to keep
// extra state to ensure we only call it once.
class SourceTrack final : public perfetto::Track {
 public:
  SourceTrack(uint64_t uuid,
              perfetto::Track parent_track,
              perfetto::StaticString source_type_string)
      : Track(uuid, parent_track), source_type_string_(source_type_string) {}

  void Serialize(
      perfetto::protos::pbzero::TrackDescriptor* track_descriptor) const {
    const auto bytes = Serialize().SerializeAsString();
    track_descriptor->AppendRawProtoBytes(bytes.data(), bytes.size());
  }
  perfetto::protos::gen::TrackDescriptor Serialize() const {
    auto track_descriptor = Track::Serialize();
    // We add a reasonably unique random string at the end of the track name
    // to prevent the Perfetto UI from incorrectly merging identically-named
    // tracks, which would be confusing in our case (e.g. separate independent
    // URL requests being incorrectly stacked on top of each other). See
    // https://crbug.com/417420482.
    //
    // Note this means the name is not really static, but it's fine to treat it
    // as such as the dynamic part obviously doesn't carry any sensitive
    // information.
    track_descriptor.set_static_name(base::StringPrintf(
        "%s %04x", source_type_string_.value, uuid % 0xFFFF));
    return track_descriptor;
  }

 private:
  perfetto::StaticString source_type_string_;
};

perfetto::StaticString SourceTypeToStaticString(NetLogSourceType source_type) {
  return perfetto::StaticString(NetLog::SourceTypeToString(source_type));
}

}  // namespace

TraceNetLogObserver::TraceNetLogObserver(Options options)
    : capture_mode_(options.capture_mode),
      use_sensitive_category_(options.use_sensitive_category),
      verbose_(options.verbose),
      root_track_name_(options.root_track_name) {}

TraceNetLogObserver::~TraceNetLogObserver() {
  DCHECK(!net_log_to_watch_);
  DCHECK(!net_log());
}

perfetto::Track TraceNetLogObserver::MaybeSetUpAndGetRootTrack() {
  // -1 to prevent conflicts with source tracks (which use positive offsets).
  perfetto::Track root_track(track_id_base_ - 1);
  std::call_once(root_track_set_up_, [&] {
    auto root_track_descriptor = root_track.Serialize();
    root_track_descriptor.set_static_name(root_track_name_.value);
    root_track_descriptor.set_child_ordering(
        perfetto::protos::gen::TrackDescriptor::CHRONOLOGICAL);
    base::TrackEvent::SetTrackDescriptor(root_track, root_track_descriptor);
  });
  return root_track;
}

void TraceNetLogObserver::OnAddEntry(const NetLogEntry& entry) {
  base::Value::Dict params = entry.params.Clone();
  // Add source's start time as a parameter. The net-log viewer requires it.
  params.Set("source_start_time",
             NetLog::TickCountToString(entry.source.start_time));
  const perfetto::StaticString entry_type_string(
      NetLogEventTypeToString(entry.type));
  const auto source_type_string = SourceTypeToStaticString(entry.source.type);

  if (verbose_) {
    AddEntryVerbose(entry, entry_type_string, source_type_string,
                    std::move(params));
  } else {
    AddEntry(entry, entry_type_string, source_type_string, std::move(params));
  }
}

void TraceNetLogObserver::AddEntry(const NetLogEntry& entry,
                                   perfetto::StaticString entry_type_string,
                                   perfetto::StaticString source_type_string,
                                   base::Value::Dict params) {
  const perfetto::Track track(track_id_base_ + entry.source.id,
                              MaybeSetUpAndGetRootTrack());
  switch (entry.phase) {
    case NetLogEventPhase::BEGIN:
      TRACE_EVENT_BEGIN(kNetLogTracingCategory, entry_type_string, track,
                        "source_type", source_type_string, "params",
                        std::make_unique<TracedValue>(std::move(params)));
      break;
    case NetLogEventPhase::END:
      TRACE_EVENT_END(kNetLogTracingCategory, track, "params",
                      std::make_unique<TracedValue>(std::move(params)));
      break;
    case NetLogEventPhase::NONE:
      TRACE_EVENT_INSTANT(kNetLogTracingCategory, entry_type_string, track,
                          "source_type", source_type_string, "params",
                          std::make_unique<TracedValue>(std::move(params)));
      break;
  }
}

void TraceNetLogObserver::AddEntryVerbose(
    const NetLogEntry& entry,
    perfetto::StaticString entry_type_string,
    perfetto::StaticString source_type_string,
    base::Value::Dict params) {
  const auto get_source_track = [&](uint32_t source_id,
                                    perfetto::StaticString source_type_string) {
    return SourceTrack(track_id_base_ + entry.source.id,
                       MaybeSetUpAndGetRootTrack(), source_type_string);
  };
  const auto track = get_source_track(entry.source.id, source_type_string);

  // We use Perfetto Flows to relate the entry back to the thread that caused it
  // be logged (typically, the network thread). This bridges the gap between
  // thread call stacks and NetLog, allowing users to correlate them.
  //
  // To provide anchor points for the flow, we write instant events on the
  // current thread stack.
  //
  // For "instant" events (NetLogEventPhase::NONE), we simply generate a random
  // flow ID. The flow starts from the instant event we are writing to the
  // current thread, and terminates on the NetLog event.
  //
  // For non-instant events, it's a bit trickier. For maximum readability, we
  // want the flow to start from the instant event we are writing to the current
  // thread for the BEGIN entry, go through the NetLog event, and then terminate
  // on a separate thread event for the END entry. This means we need to use the
  // same flow ID for BEGIN and END entries. There is no obvious ID we can use
  // that would be identical between the two entries. The approach we use here
  // is to generate the flow ID from the Track ID and the NetLog event type.
  // This will work as long as a given Track doesn't have two NetLog events that
  // are the same type *and* overlap in time. If this assumption breaks, we will
  // need to revisit this approach; we may need to track additional state.
  const auto thread_event_name_str = base::StringPrintf(
      "%s: %s%s/%s", root_track_name_.value,
      [&] {
        switch (entry.phase) {
          case NetLogEventPhase::BEGIN:
            return "BEGIN ";
          case NetLogEventPhase::END:
            return "END ";
          case NetLogEventPhase::NONE:
            return "";
        }
      }(),
      source_type_string.value, entry_type_string.value);
  // Note: the separate variable is load-bearing, as DynamicString will not
  // retain the std::string. See https://crbug.com/417982839.
  const perfetto::DynamicString thread_event_name(thread_event_name_str);
  const uint64_t thread_flow_id =
      entry.phase == NetLogEventPhase::NONE
          ? base::RandUint64()
          : track.uuid + std::hash<std::string_view>()(std::string_view(
                             reinterpret_cast<const char*>(&entry.type),
                             sizeof(entry.type)));
  if (entry.phase != NetLogEventPhase::END) {
    TRACE_EVENT_INSTANT(kNetLogTracingCategory, thread_event_name,
                        perfetto::Flow::ProcessScoped(thread_flow_id));
  } else {
    TRACE_EVENT_INSTANT(
        kNetLogTracingCategory, thread_event_name,
        perfetto::TerminatingFlow::ProcessScoped(thread_flow_id));
  }
  const auto add_thread_flow = [&](perfetto::EventContext& event_context) {
    switch (entry.phase) {
      case NetLogEventPhase::BEGIN:
        perfetto::Flow::ProcessScoped(thread_flow_id)(event_context);
        break;
      case NetLogEventPhase::END:
        // No need to add the flow: we already added it to this event while
        // processing the BEGIN entry.
        break;
      case NetLogEventPhase::NONE:
        perfetto::TerminatingFlow::ProcessScoped(thread_flow_id)(event_context);
        break;
    }
  };

  // The tracing category must be a compile-time constant, hence the macro to
  // handle the sensitive vs non-sensitive categories.
#define CALL_TRACE_EVENT(TRACE_EVENT, ...)                       \
  do {                                                           \
    if (use_sensitive_category_) {                               \
      TRACE_EVENT(kSensitiveNetLogTracingCategory, __VA_ARGS__); \
    } else {                                                     \
      TRACE_EVENT(kNetLogTracingCategory, __VA_ARGS__);          \
    }                                                            \
  } while (false)

  // We use Perfetto Flows to represent source dependencies; these will show up
  // as arrows in the Perfetto UI. The dependency is on a source, i.e. a track,
  // but Perfetto flows start from an event, not a track. To work around this we
  // write a made-up instant event on the source dependency track to act as an
  // anchor for the flow.
  std::optional<uint64_t> source_dependency_flow_id;
  const base::DictValue* const source_dependency =
      params.FindDict("source_dependency");
  if (source_dependency != nullptr) {
    const std::optional<int> source_dependency_id =
        source_dependency->FindInt("id");
    const std::optional<int> source_dependency_type =
        source_dependency->FindInt("type");
    if (source_dependency_id.has_value() &&
        source_dependency_type.has_value()) {
      source_dependency_flow_id = base::RandUint64();
      CALL_TRACE_EVENT(
          TRACE_EVENT_INSTANT, entry_type_string,
          get_source_track(
              *source_dependency_id,
              SourceTypeToStaticString(
                  static_cast<NetLogSourceType>(*source_dependency_type))),
          perfetto::Flow::ProcessScoped(*source_dependency_flow_id));
    }
  }
  const auto maybe_add_source_dependency_flow =
      [&](perfetto::EventContext& event_context) {
        if (source_dependency_flow_id.has_value()) {
          perfetto::TerminatingFlow::ProcessScoped (*source_dependency_flow_id)(
              event_context);
        }
      };

  const auto set_event_fields = [&](perfetto::EventContext& event_context) {
    add_thread_flow(event_context);
    maybe_add_source_dependency_flow(event_context);
  };

  switch (entry.phase) {
    case NetLogEventPhase::BEGIN:
      CALL_TRACE_EVENT(TRACE_EVENT_BEGIN, entry_type_string, track,
                       set_event_fields, "source_type", source_type_string,
                       "params",
                       std::make_unique<TracedValue>(std::move(params)));
      break;
    case NetLogEventPhase::END:
      CALL_TRACE_EVENT(TRACE_EVENT_END, track, set_event_fields, "params",
                       std::make_unique<TracedValue>(std::move(params)));
      break;
    case NetLogEventPhase::NONE:
      CALL_TRACE_EVENT(TRACE_EVENT_INSTANT, entry_type_string, track,
                       set_event_fields, "source_type", source_type_string,
                       "params",
                       std::make_unique<TracedValue>(std::move(params)));
      break;
  }

#undef CALL_TRACE_EVENT
}

void TraceNetLogObserver::WatchForTraceStart(NetLog* netlog) {
  DCHECK(!net_log_to_watch_);
  DCHECK(!net_log());
  net_log_to_watch_ = netlog;
  // Tracing can start before the observer is even created, for instance for
  // startup tracing.
  if (base::trace_event::TraceLog::GetInstance()->IsEnabled())
    OnTraceLogEnabled();
  base::trace_event::TraceLog::GetInstance()->AddAsyncEnabledStateObserver(
      weak_factory_.GetWeakPtr());
}

void TraceNetLogObserver::StopWatchForTraceStart() {
  // Should only stop if is currently watching.
  DCHECK(net_log_to_watch_);
  base::trace_event::TraceLog::GetInstance()->RemoveAsyncEnabledStateObserver(
      this);
  // net_log() != nullptr iff NetLog::AddObserver() has been called.
  // This implies that if the netlog category wasn't enabled, then
  // NetLog::RemoveObserver() will not get called, and there won't be
  // a crash in NetLog::RemoveObserver().
  if (net_log())
    net_log()->RemoveObserver(this);
  net_log_to_watch_ = nullptr;
}

void TraceNetLogObserver::OnTraceLogEnabled() {
  bool enabled;
  TRACE_EVENT_CATEGORY_GROUP_ENABLED(kNetLogTracingCategory, &enabled);
  if (!enabled)
    return;

  net_log_to_watch_->AddObserver(this, capture_mode_);
}

void TraceNetLogObserver::OnTraceLogDisabled() {
  if (net_log())
    net_log()->RemoveObserver(this);
}

}  // namespace net