summaryrefslogtreecommitdiff
path: root/chromium/components/data_use_measurement/core/data_use_measurement.cc
blob: 3a8030740154a3c328070d3c0ca6ada8614c6ad1 (plain)
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/data_use_measurement/core/data_use_measurement.h"

#include "base/metrics/histogram_macros.h"
#include "base/metrics/sparse_histogram.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "components/data_use_measurement/core/data_use_ascriber.h"
#include "components/data_use_measurement/core/data_use_recorder.h"
#include "components/data_use_measurement/core/data_use_user_data.h"
#include "components/data_use_measurement/core/url_request_classifier.h"
#include "components/domain_reliability/uploader.h"
#include "google_apis/gaia/gaia_auth_util.h"
#include "net/base/network_change_notifier.h"
#include "net/base/upload_data_stream.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"

#if defined(OS_ANDROID)
#include "net/android/traffic_stats.h"
#endif

namespace data_use_measurement {

namespace {

// Records the occurrence of |sample| in |name| histogram. Conventional UMA
// histograms are not used because the |name| is not static.
void RecordUMAHistogramCount(const std::string& name, int64_t sample) {
  base::HistogramBase* histogram_pointer = base::Histogram::FactoryGet(
      name,
      1,        // Minimum sample size in bytes.
      1000000,  // Maximum sample size in bytes. Should cover most of the
                // requests by services.
      50,       // Bucket count.
      base::HistogramBase::kUmaTargetedHistogramFlag);
  histogram_pointer->Add(sample);
}

// This function increases the value of |sample| bucket in |name| sparse
// histogram by |value|. Conventional UMA histograms are not used because |name|
// is not static.
void IncreaseSparseHistogramByValue(const std::string& name,
                                    int64_t sample,
                                    int64_t value) {
  base::HistogramBase* histogram = base::SparseHistogram::FactoryGet(
      name, base::HistogramBase::kUmaTargetedHistogramFlag);
  histogram->AddCount(sample, value);
}

#if defined(OS_ANDROID)
void IncrementLatencyHistogramByCount(const std::string& name,
                                      const base::TimeDelta& latency,
                                      int64_t count) {
  base::HistogramBase* histogram_pointer = base::Histogram::FactoryTimeGet(
      name,
      base::TimeDelta::FromMilliseconds(1),  // Minimum sample
      base::TimeDelta::FromHours(1),         // Maximum sample
      50,                                    // Bucket count.
      base::HistogramBase::kUmaTargetedHistogramFlag);
  histogram_pointer->AddCount(latency.InMilliseconds(), count);
}
#endif

}  // namespace

DataUseMeasurement::DataUseMeasurement(
    std::unique_ptr<URLRequestClassifier> url_request_classifier,
    const metrics::UpdateUsagePrefCallbackType& metrics_data_use_forwarder,
    DataUseAscriber* ascriber)
    : url_request_classifier_(std::move(url_request_classifier)),
      metrics_data_use_forwarder_(metrics_data_use_forwarder),
      ascriber_(ascriber)
#if defined(OS_ANDROID)
      ,
      app_state_(base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES),
      app_listener_(new base::android::ApplicationStatusListener(
          base::Bind(&DataUseMeasurement::OnApplicationStateChange,
                     base::Unretained(this)))),
      rx_bytes_os_(0),
      tx_bytes_os_(0),
      bytes_transferred_since_last_traffic_stats_query_(0),
      no_reads_since_background_(false)
#endif
{
  DCHECK(ascriber_);
  DCHECK(url_request_classifier_);

#if defined(OS_ANDROID)
  int64_t bytes = 0;
  // Query Android traffic stats.
  if (net::android::traffic_stats::GetCurrentUidRxBytes(&bytes))
    rx_bytes_os_ = bytes;

  if (net::android::traffic_stats::GetCurrentUidTxBytes(&bytes))
    tx_bytes_os_ = bytes;
#endif
}

DataUseMeasurement::~DataUseMeasurement(){};

void DataUseMeasurement::OnBeforeURLRequest(net::URLRequest* request) {
  DataUseUserData* data_use_user_data = reinterpret_cast<DataUseUserData*>(
      request->GetUserData(DataUseUserData::kUserDataKey));
  if (!data_use_user_data) {
    DataUseUserData::ServiceName service_name =
        DataUseUserData::ServiceName::NOT_TAGGED;
    if (!url_request_classifier_->IsUserRequest(*request) &&
        domain_reliability::DomainReliabilityUploader::
            OriginatedFromDomainReliability(*request)) {
      // Detect if the request originated from DomainReliability.
      // DataUseUserData::AttachToFetcher() cannot be called from domain
      // reliability, since it sets userdata on URLFetcher for its purposes.
      service_name = DataUseUserData::ServiceName::DOMAIN_RELIABILITY;
    } else if (gaia::RequestOriginatedFromGaia(*request)) {
      service_name = DataUseUserData::ServiceName::GAIA;
    }

    data_use_user_data = new DataUseUserData(service_name, CurrentAppState());
    request->SetUserData(DataUseUserData::kUserDataKey, data_use_user_data);
  } else {
    data_use_user_data->set_app_state(CurrentAppState());
  }
}

void DataUseMeasurement::OnBeforeRedirect(const net::URLRequest& request,
                                          const GURL& new_location) {
  // Recording data use of request on redirects.
  // TODO(rajendrant): May not be needed when http://crbug/651957 is fixed.
  UpdateDataUsePrefs(request);
  ReportServicesMessageSizeUMA(request);
}

void DataUseMeasurement::OnHeadersReceived(
    net::URLRequest* request,
    const net::HttpResponseHeaders* response_headers) {
  DataUseUserData* data_use_user_data = reinterpret_cast<DataUseUserData*>(
      request->GetUserData(DataUseUserData::kUserDataKey));
  if (data_use_user_data) {
    data_use_user_data->set_content_type(
        url_request_classifier_->GetContentType(*request, *response_headers));
  }
}

void DataUseMeasurement::OnNetworkBytesReceived(const net::URLRequest& request,
                                                int64_t bytes_received) {
  UMA_HISTOGRAM_COUNTS("DataUse.BytesReceived.Delegate", bytes_received);
  ReportDataUseUMA(request, DOWNSTREAM, bytes_received);
#if defined(OS_ANDROID)
  bytes_transferred_since_last_traffic_stats_query_ += bytes_received;
#endif
}

void DataUseMeasurement::OnNetworkBytesSent(const net::URLRequest& request,
                                            int64_t bytes_sent) {
  UMA_HISTOGRAM_COUNTS("DataUse.BytesSent.Delegate", bytes_sent);
  ReportDataUseUMA(request, UPSTREAM, bytes_sent);
#if defined(OS_ANDROID)
  bytes_transferred_since_last_traffic_stats_query_ += bytes_sent;
#endif
}

void DataUseMeasurement::OnCompleted(const net::URLRequest& request,
                                     bool started) {
  // TODO(amohammadkhan): Verify that there is no double recording in data use
  // of redirected requests.
  UpdateDataUsePrefs(request);
  ReportServicesMessageSizeUMA(request);
#if defined(OS_ANDROID)
  MaybeRecordNetworkBytesOS();
#endif
}

void DataUseMeasurement::ReportDataUseUMA(const net::URLRequest& request,
                                          TrafficDirection dir,
                                          int64_t bytes) {
  bool is_user_traffic = url_request_classifier_->IsUserRequest(request);
  bool is_connection_cellular =
      net::NetworkChangeNotifier::IsConnectionCellular(
          net::NetworkChangeNotifier::GetConnectionType());

  DataUseUserData* attached_service_data = static_cast<DataUseUserData*>(
      request.GetUserData(DataUseUserData::kUserDataKey));
  DataUseUserData::AppState old_app_state = DataUseUserData::FOREGROUND;
  DataUseUserData::AppState new_app_state = DataUseUserData::UNKNOWN;

  if (attached_service_data)
    old_app_state = attached_service_data->app_state();

  if (old_app_state == CurrentAppState())
    new_app_state = old_app_state;

  if (attached_service_data && old_app_state != new_app_state)
    attached_service_data->set_app_state(CurrentAppState());

  RecordUMAHistogramCount(
      GetHistogramName(is_user_traffic ? "DataUse.TrafficSize.User"
                                       : "DataUse.TrafficSize.System",
                       dir, new_app_state, is_connection_cellular),
      bytes);

#if defined(OS_ANDROID)
  if (dir == DOWNSTREAM && CurrentAppState() == DataUseUserData::BACKGROUND) {
    DCHECK(!last_app_background_time_.is_null());

    const base::TimeDelta time_since_background =
        base::TimeTicks::Now() - last_app_background_time_;
    IncrementLatencyHistogramByCount(
        is_user_traffic ? "DataUse.BackgroundToDataRecievedPerByte.User"
                        : "DataUse.BackgroundToDataRecievedPerByte.System",
        time_since_background, bytes);
    if (no_reads_since_background_) {
      no_reads_since_background_ = false;
      IncrementLatencyHistogramByCount(
          is_user_traffic ? "DataUse.BackgroundToFirstDownstream.User"
                          : "DataUse.BackgroundToFirstDownstream.System",
          time_since_background, 1);
    }
  }
#endif

  bool is_tab_visible = false;

  if (is_user_traffic) {
    const DataUseRecorder* recorder = ascriber_->GetDataUseRecorder(request);
    if (recorder) {
      is_tab_visible = recorder->is_visible();
      RecordTabStateHistogram(dir, new_app_state, recorder->is_visible(),
                              bytes);
    }
  }
  if (attached_service_data && dir == DOWNSTREAM &&
      new_app_state != DataUseUserData::UNKNOWN) {
    RecordContentTypeHistogram(attached_service_data->content_type(),
                               is_user_traffic, new_app_state, is_tab_visible,
                               bytes);
  }
}

void DataUseMeasurement::UpdateDataUsePrefs(
    const net::URLRequest& request) const {
  bool is_connection_cellular =
      net::NetworkChangeNotifier::IsConnectionCellular(
          net::NetworkChangeNotifier::GetConnectionType());

  DataUseUserData* attached_service_data = static_cast<DataUseUserData*>(
      request.GetUserData(DataUseUserData::kUserDataKey));
  DataUseUserData::ServiceName service_name =
      attached_service_data ? attached_service_data->service_name()
                            : DataUseUserData::NOT_TAGGED;

  // Update data use prefs for cellular connections.
  if (!metrics_data_use_forwarder_.is_null()) {
    metrics_data_use_forwarder_.Run(
        DataUseUserData::GetServiceNameAsString(service_name),
        request.GetTotalSentBytes() + request.GetTotalReceivedBytes(),
        is_connection_cellular);
  }
}

#if defined(OS_ANDROID)
void DataUseMeasurement::OnApplicationStateChangeForTesting(
    base::android::ApplicationState application_state) {
  OnApplicationStateChange(application_state);
}
#endif

DataUseUserData::AppState DataUseMeasurement::CurrentAppState() const {
#if defined(OS_ANDROID)
  if (app_state_ != base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES)
    return DataUseUserData::BACKGROUND;
#endif
  // If the OS is not Android, all the requests are considered Foreground.
  return DataUseUserData::FOREGROUND;
}

std::string DataUseMeasurement::GetHistogramName(
    const char* prefix,
    TrafficDirection dir,
    DataUseUserData::AppState app_state,
    bool is_connection_cellular) const {
  return base::StringPrintf(
      "%s.%s.%s.%s", prefix, dir == UPSTREAM ? "Upstream" : "Downstream",
      app_state == DataUseUserData::UNKNOWN
          ? "Unknown"
          : (app_state == DataUseUserData::FOREGROUND ? "Foreground"
                                                      : "Background"),
      is_connection_cellular ? "Cellular" : "NotCellular");
}

#if defined(OS_ANDROID)
void DataUseMeasurement::OnApplicationStateChange(
    base::android::ApplicationState application_state) {
  app_state_ = application_state;
  if (app_state_ != base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES) {
    last_app_background_time_ = base::TimeTicks::Now();
    no_reads_since_background_ = true;
    MaybeRecordNetworkBytesOS();
  } else {
    last_app_background_time_ = base::TimeTicks();
  }
}

void DataUseMeasurement::MaybeRecordNetworkBytesOS() {
  // Minimum number of bytes that should be reported by the network delegate
  // before Android's TrafficStats API is queried (if Chrome is not in
  // background). This reduces the overhead of repeatedly calling the API.
  static const int64_t kMinDelegateBytes = 25000;

  if (bytes_transferred_since_last_traffic_stats_query_ < kMinDelegateBytes &&
      CurrentAppState() == DataUseUserData::FOREGROUND) {
    return;
  }
  bytes_transferred_since_last_traffic_stats_query_ = 0;
  int64_t bytes = 0;
  // Query Android traffic stats directly instead of registering with the
  // DataUseAggregator since the latter does not provide notifications for
  // the incognito traffic.
  if (net::android::traffic_stats::GetCurrentUidRxBytes(&bytes)) {
    if (rx_bytes_os_ != 0) {
      DCHECK_GE(bytes, rx_bytes_os_);
      if (bytes > rx_bytes_os_) {
        // Do not record samples with value 0.
        UMA_HISTOGRAM_COUNTS("DataUse.BytesReceived.OS", bytes - rx_bytes_os_);
      }
    }
    rx_bytes_os_ = bytes;
  }

  if (net::android::traffic_stats::GetCurrentUidTxBytes(&bytes)) {
    if (tx_bytes_os_ != 0) {
      DCHECK_GE(bytes, tx_bytes_os_);
      if (bytes > tx_bytes_os_) {
        // Do not record samples with value 0.
        UMA_HISTOGRAM_COUNTS("DataUse.BytesSent.OS", bytes - tx_bytes_os_);
      }
    }
    tx_bytes_os_ = bytes;
  }
}
#endif

void DataUseMeasurement::ReportServicesMessageSizeUMA(
    const net::URLRequest& request) {
  bool is_user_traffic = url_request_classifier_->IsUserRequest(request);
  bool is_connection_cellular =
      net::NetworkChangeNotifier::IsConnectionCellular(
          net::NetworkChangeNotifier::GetConnectionType());

  DataUseUserData* attached_service_data = static_cast<DataUseUserData*>(
      request.GetUserData(DataUseUserData::kUserDataKey));
  DataUseUserData::ServiceName service_name = DataUseUserData::NOT_TAGGED;

  if (attached_service_data)
    service_name = attached_service_data->service_name();

  if (!is_user_traffic) {
    ReportDataUsageServices(service_name, UPSTREAM, CurrentAppState(),
                            is_connection_cellular,
                            request.GetTotalSentBytes());
    ReportDataUsageServices(service_name, DOWNSTREAM, CurrentAppState(),
                            is_connection_cellular,
                            request.GetTotalReceivedBytes());
  }
}

void DataUseMeasurement::ReportDataUsageServices(
    DataUseUserData::ServiceName service,
    TrafficDirection dir,
    DataUseUserData::AppState app_state,
    bool is_connection_cellular,
    int64_t message_size) const {
  RecordUMAHistogramCount(
      "DataUse.MessageSize." + DataUseUserData::GetServiceNameAsString(service),
      message_size);
  if (message_size > 0) {
    IncreaseSparseHistogramByValue(
        GetHistogramName("DataUse.MessageSize.AllServices", dir, app_state,
                         is_connection_cellular),
        service, message_size);
  }
}

void DataUseMeasurement::RecordTabStateHistogram(
    TrafficDirection dir,
    DataUseUserData::AppState app_state,
    bool is_tab_visible,
    int64_t bytes) {
  if (app_state == DataUseUserData::UNKNOWN)
    return;

  std::string histogram_name = "DataUse.AppTabState.";
  histogram_name.append(dir == UPSTREAM ? "Upstream." : "Downstream.");
  if (app_state == DataUseUserData::BACKGROUND) {
    histogram_name.append("AppBackground");
  } else if (is_tab_visible) {
    histogram_name.append("AppForeground.TabForeground");
  } else {
    histogram_name.append("AppForeground.TabBackground");
  }
  RecordUMAHistogramCount(histogram_name, bytes);
}

void DataUseMeasurement::RecordContentTypeHistogram(
    DataUseUserData::DataUseContentType content_type,
    bool is_user_traffic,
    DataUseUserData::AppState app_state,
    bool is_tab_visible,
    int64_t bytes) {
  if (content_type == DataUseUserData::AUDIO) {
    content_type = app_state != DataUseUserData::FOREGROUND
                       ? DataUseUserData::AUDIO_APPBACKGROUND
                       : (!is_tab_visible ? DataUseUserData::AUDIO_TABBACKGROUND
                                          : DataUseUserData::AUDIO);
  } else if (content_type == DataUseUserData::VIDEO) {
    content_type = app_state != DataUseUserData::FOREGROUND
                       ? DataUseUserData::VIDEO_APPBACKGROUND
                       : (!is_tab_visible ? DataUseUserData::VIDEO_TABBACKGROUND
                                          : DataUseUserData::VIDEO);
  }
  // Use the more primitive STATIC_HISTOGRAM_POINTER_BLOCK macro because the
  // simple UMA_HISTOGRAM_ENUMERATION macros don't expose 'AddCount'.
  if (is_user_traffic) {
    STATIC_HISTOGRAM_POINTER_BLOCK(
        "DataUse.ContentType.UserTraffic", AddCount(content_type, bytes),
        base::LinearHistogram::FactoryGet(
            "DataUse.ContentType.UserTraffic", 1, DataUseUserData::TYPE_MAX,
            DataUseUserData::TYPE_MAX + 1,
            base::HistogramBase::kUmaTargetedHistogramFlag));
  } else {
    STATIC_HISTOGRAM_POINTER_BLOCK(
        "DataUse.ContentType.Services", AddCount(content_type, bytes),
        base::LinearHistogram::FactoryGet(
            "DataUse.ContentType.Services", 1, DataUseUserData::TYPE_MAX,
            DataUseUserData::TYPE_MAX + 1,
            base::HistogramBase::kUmaTargetedHistogramFlag));
  }
}

}  // namespace data_use_measurement