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 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_LOG_NET_LOG_H_
#define NET_LOG_NET_LOG_H_
#include <stdint.h>
#include <atomic>
#include <concepts>
#include <string>
#include <vector>
#include "base/compiler_specific.h"
#include "base/functional/function_ref.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ref.h"
#include "base/synchronization/lock.h"
#include "base/time/time.h"
#include "base/types/pass_key.h"
#include "base/values.h"
#include "build/build_config.h"
#include "net/base/net_export.h"
#include "net/log/net_log_capture_mode.h"
#include "net/log/net_log_entry.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_source.h"
#include "net/log/net_log_source_type.h"
namespace net {
class NetLogWithSource;
// NetLog is the destination for log messages generated by the network stack.
// Each log message has a "source" field which identifies the specific entity
// that generated the message (for example, which URLRequest or which
// SpdySession).
//
// To avoid needing to pass in the "source ID" to the logging functions, NetLog
// is usually accessed through a NetLogWithSource, which will always pass in a
// specific source ID.
//
// All methods on NetLog are thread safe, with the exception that no NetLog or
// NetLog::ThreadSafeObserver functions may be called by an observer's
// OnAddEntry() method, as doing so will result in a deadlock.
//
// For a broader introduction see the design document:
// https://sites.google.com/a/chromium.org/dev/developers/design-documents/network-stack/netlog
//
// ==================================
// Materializing parameters
// ==================================
//
// Events can contain a JSON serializable base::Value [1] referred to as its
// "parameters".
//
// Functions for emitting events have overloads that take a |get_params|
// argument for this purpose.
//
// |get_params| is essentially a block of code to conditionally execute when
// the parameters need to be materialized. It is most easily specified as a C++
// lambda.
//
// This idiom for specifying parameters avoids spending time building the
// base::Value when capturing is off. For instance when specified as a lambda
// that takes 0 arguments, the inlined code from template expansion roughly
// does:
//
// if (net_log->IsCapturing()) {
// base::Value params = get_params();
// net_log->EmitEventToAllObsevers(type, source, phase, std::move(params));
// }
//
// Alternately, the |get_params| argument could be an invocable that takes a
// NetLogCaptureMode parameter:
//
// base::Value params = get_params(capture_mode);
//
// In this case, |get_params| depends on the logging granularity and would be
// called once per observed NetLogCaptureMode.
//
// [1] Being "JSON serializable" means you cannot use
// base::Value::Type::BINARY. Instead use NetLogBinaryValue() to repackage
// it as a base::Value::Type::STRING.
class NET_EXPORT NetLog {
public:
// An observer that is notified of entries added to the NetLog. The
// "ThreadSafe" prefix of the name emphasizes that this observer may be
// called from different threads then the one which added it as an observer.
class NET_EXPORT ThreadSafeObserver {
public:
// Constructs an observer that wants to see network events, with
// the specified minimum event granularity. A ThreadSafeObserver can only
// observe a single NetLog at a time.
//
// Observers will be called on the same thread an entry is added on,
// and are responsible for ensuring their own thread safety.
//
// Observers must stop watching a NetLog before either the observer or the
// NetLog is destroyed.
ThreadSafeObserver();
ThreadSafeObserver(const ThreadSafeObserver&) = delete;
ThreadSafeObserver& operator=(const ThreadSafeObserver&) = delete;
// Returns the capture mode for events this observer wants to
// receive. It is only valid to call this while observing a NetLog.
NetLogCaptureMode capture_mode() const;
// Returns the NetLog being watched, or nullptr if there is none.
NetLog* net_log() const;
// This method is called whenever an entry (event) was added to the NetLog
// being watched.
//
// OnAddEntry() is invoked on the thread which generated the NetLog entry,
// which may be different from the thread that added this observer.
//
// Whenever OnAddEntry() is invoked, the NetLog's mutex is held. The
// consequences of this are:
//
// * OnAddEntry() will never be called concurrently -- implementations
// can rely on this to avoid needing their own synchronization.
//
// * It is illegal for an observer to call back into the NetLog, or the
// observer itself, as this can result in deadlock or violating
// expectations of non re-entrancy into ThreadSafeObserver.
virtual void OnAddEntry(const NetLogEntry& entry) = 0;
protected:
virtual ~ThreadSafeObserver();
private:
friend class NetLog;
// Both of these values are only modified by the NetLog.
NetLogCaptureMode capture_mode_ = NetLogCaptureMode::kDefault;
raw_ptr<NetLog> net_log_ = nullptr;
};
// An observer that is notified of changes in the capture mode set, and has
// the ability to add NetLog entries with materialized params.
class NET_EXPORT ThreadSafeCaptureModeObserver {
public:
ThreadSafeCaptureModeObserver();
ThreadSafeCaptureModeObserver(const ThreadSafeCaptureModeObserver&) =
delete;
ThreadSafeCaptureModeObserver& operator=(
const ThreadSafeCaptureModeObserver&) = delete;
virtual void OnCaptureModeUpdated(NetLogCaptureModeSet modes) = 0;
protected:
virtual ~ThreadSafeCaptureModeObserver();
NetLogCaptureModeSet GetObserverCaptureModes() const;
// Add event to the observed NetLog. Must only be called while observing is
// active, and the caller is responsible for ensuring the materialized
// params are suitable for the current capture mode.
void AddEntryAtTimeWithMaterializedParams(NetLogEventType type,
const NetLogSource& source,
NetLogEventPhase phase,
base::TimeTicks time,
base::Value::Dict params);
private:
// Friend NetLog so that AddCaptureModeObserver/RemoveCaptureModeObserver
// can update the |net_log_| member.
friend class NetLog;
// This value is only modified by the NetLog.
raw_ptr<NetLog> net_log_ = nullptr;
};
// Returns the singleton NetLog object, which is never destructed and which
// may be used on any thread.
static NetLog* Get();
// NetLog should only be used through the singleton returned by Get(), the
// constructor takes a PassKey to ensure that additional NetLog objects
// cannot be created.
explicit NetLog(base::PassKey<NetLog>);
// NetLogWithSource creates a dummy NetLog as an internal optimization.
explicit NetLog(base::PassKey<NetLogWithSource>);
NetLog(const NetLog&) = delete;
NetLog& operator=(const NetLog&) = delete;
~NetLog() = delete;
// Configure the source IDs returned by NextID() to use a different starting
// position, so that NetLog events generated by this process will not conflict
// with those generated by another NetLog in a different process. This
// should only be called once, before any NetLogSource could be created in
// the current process.
//
// Currently only a single additional source id partition is supported.
void InitializeSourceIdPartition();
void AddEntry(NetLogEventType type,
const NetLogSource& source,
NetLogEventPhase phase);
// Adds an entry for the given source, phase, and type, whose parameters are
// obtained by invoking |get_params()| with no arguments.
//
// See "Materializing parameters" for details.
template <typename ParametersCallback>
requires(!std::invocable<ParametersCallback, NetLogCaptureMode>)
inline void AddEntry(NetLogEventType type,
const NetLogSource& source,
NetLogEventPhase phase,
const ParametersCallback& get_params) {
if (!IsCapturing()) [[likely]] {
return;
}
AddEntryWithMaterializedParams(type, source, phase, get_params());
}
// Adds an entry for the given source, phase, and type, whose parameters are
// obtained by invoking |get_params(capture_mode)| with a NetLogCaptureMode.
//
// See "Materializing parameters" for details.
template <typename ParametersCallback>
requires(std::invocable<ParametersCallback, NetLogCaptureMode>)
inline void AddEntry(NetLogEventType type,
const NetLogSource& source,
NetLogEventPhase phase,
const ParametersCallback& get_params) {
if (!IsCapturing()) [[likely]] {
return;
}
AddEntryInternal(type, source, phase, get_params);
}
// Emits a global event to the log stream, with its own unique source ID.
void AddGlobalEntry(NetLogEventType type);
// Overload of AddGlobalEntry() that includes parameters.
//
// See "Materializing parameters" for details on |get_params|.
template <typename ParametersCallback>
void AddGlobalEntry(NetLogEventType type,
const ParametersCallback& get_params) {
AddEntry(type, NetLogSource(NetLogSourceType::NONE, NextID()),
NetLogEventPhase::NONE, get_params);
}
void AddGlobalEntryWithStringParams(NetLogEventType type,
std::string_view name,
std::string_view value);
// Returns a unique ID which can be used as a source ID. All returned IDs
// will be unique and not equal to 0.
uint32_t NextID();
// Returns true if there are any observers attached to the NetLog.
//
// TODO(eroman): Survey current callsites; most are probably not necessary,
// and may even be harmful.
bool IsCapturing() const {
return GetObserverCaptureModes() != 0;
}
// Adds an observer and sets its log capture mode. The observer must not be
// watching any NetLog, including this one, when this is called.
//
// CAUTION: Think carefully before introducing a dependency on the
// NetLog. The order, format, and parameters in NetLog events are NOT
// guaranteed to be stable. As such, building a production feature that works
// by observing the NetLog is likely inappropriate. Just as you wouldn't build
// a feature by scraping the text output from LOG(INFO), you shouldn't do
// the same by scraping the logging data emitted to NetLog. Support for
// observers is an internal detail mainly used for testing and to write events
// to a file. Please consult a //net OWNER before using this outside of
// testing or serialization.
void AddObserver(ThreadSafeObserver* observer,
NetLogCaptureMode capture_mode);
// Removes an observer.
//
// For thread safety reasons, it is recommended that this not be called in
// an object's destructor.
void RemoveObserver(ThreadSafeObserver* observer);
// Adds an observer that is notified of changes in the capture mode set.
void AddCaptureModeObserver(ThreadSafeCaptureModeObserver* observer);
// Removes a capture mode observer.
void RemoveCaptureModeObserver(ThreadSafeCaptureModeObserver* observer);
// Converts a time to the string format that the NetLog uses to represent
// times. Strings are used since integers may overflow.
// The resulting string contains the number of milliseconds since the origin
// or "zero" point of the TimeTicks class, which can vary each time the
// application is restarted. This number is related to an actual time via the
// timeTickOffset recorded in GetNetConstants().
static std::string TickCountToString(const base::TimeTicks& time);
// Same as above but takes a base::Time. Should not be used if precise
// timestamps are desired, but is suitable for e.g. expiration times.
static std::string TimeToString(const base::Time& time);
// Returns a dictionary that maps event type symbolic names to their enum
// values.
static base::Value GetEventTypesAsValue();
// Returns a C-String symbolic name for |source_type|.
static const char* SourceTypeToString(NetLogSourceType source_type);
// Returns a dictionary that maps source type symbolic names to their enum
// values.
static base::Value GetSourceTypesAsValue();
// Returns a C-String symbolic name for |event_phase|.
static const char* EventPhaseToString(NetLogEventPhase event_phase);
private:
// Helper for implementing AddEntry() that indirects parameter getting through
// virtual dispatch.
NOINLINE void AddEntryInternal(
NetLogEventType type,
const NetLogSource& source,
NetLogEventPhase phase,
base::FunctionRef<base::Value::Dict(NetLogCaptureMode)> get_params);
// Returns the set of all capture modes being observed.
NetLogCaptureModeSet GetObserverCaptureModes() const {
return observer_capture_modes_.load(std::memory_order_relaxed);
}
// Adds an entry using already materialized parameters, when it is already
// known that the log is capturing (goes straight to acquiring observer lock).
//
// TODO(eroman): Drop the rvalue-ref on |params| unless can show it improves
// the generated code (initial testing suggests it makes no difference in
// clang).
void AddEntryWithMaterializedParams(NetLogEventType type,
const NetLogSource& source,
NetLogEventPhase phase,
base::Value::Dict params);
// Adds an entry at a certain time, using already materialized parameters,
// when it is already known that the log is capturing (goes straight to
// acquiring observer lock).
void AddEntryAtTimeWithMaterializedParams(NetLogEventType type,
const NetLogSource& source,
NetLogEventPhase phase,
base::TimeTicks time,
base::Value::Dict params);
// Called whenever an observer is added or removed, to update
// |observer_capture_modes_|. Must have acquired |lock_| prior to calling.
void UpdateObserverCaptureModes();
// Returns true if |observer| is watching this NetLog. Must
// be called while |lock_| is already held.
bool HasObserver(ThreadSafeObserver* observer);
bool HasCaptureModeObserver(ThreadSafeCaptureModeObserver* observer);
// |lock_| protects access to |observers_|.
base::Lock lock_;
// Last assigned source ID. Incremented to get the next one.
std::atomic<int32_t> last_id_ = {};
// Holds the set of all capture modes that observers are watching the log at.
//
// Is 0 when there are no observers. Stored as an Atomic32 so it can be
// accessed and updated more efficiently.
std::atomic<NetLogCaptureModeSet> observer_capture_modes_ = {};
// |observers_| is a list of observers, ordered by when they were added.
// Pointers contained in |observers_| are non-owned, and must
// remain valid.
//
// |lock_| must be acquired whenever reading or writing to this.
//
// In practice |observers_| will be very small (<5) so O(n)
// operations on it are fine.
std::vector<raw_ptr<ThreadSafeObserver, VectorExperimental>> observers_;
std::vector<raw_ptr<ThreadSafeCaptureModeObserver, VectorExperimental>>
capture_mode_observers_;
};
} // namespace net
#endif // NET_LOG_NET_LOG_H_
|