Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(480)

Side by Side Diff: components/metrics/file_metrics_provider.cc

Issue 1537743006: Persist setup metrics and have Chrome report them during UMA upload. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@shared-histograms
Patch Set: move AccessResult to .h and add histogram to .xml Created 4 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2016 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "components/metrics/file_metrics_provider.h"
6
7 #include "base/command_line.h"
8 #include "base/files/file.h"
9 #include "base/files/file_util.h"
10 #include "base/files/memory_mapped_file.h"
11 #include "base/logging.h"
12 #include "base/metrics/histogram_base.h"
13 #include "base/metrics/histogram_macros.h"
14 #include "base/metrics/histogram_persistence.h"
15 #include "base/metrics/persistent_memory_allocator.h"
16 #include "base/task_runner.h"
17 #include "base/time/time.h"
18 #include "components/metrics/metrics_pref_names.h"
19 #include "components/metrics/metrics_service.h"
20 #include "components/prefs/pref_registry_simple.h"
21 #include "components/prefs/pref_service.h"
22
23
24 namespace metrics {
25
26 // This structure stores all the information about the files being monitored
27 // and their current reporting state.
28 struct FileMetricsProvider::FileInfo {
29 FileInfo() {}
30 ~FileInfo() {}
31
32 // Where on disk the file is located.
33 base::FilePath path;
34
35 // How to access this file (atomic/active).
36 FileType type;
37
38 // Name used inside prefs to persistent metadata.
39 std::string prefs_key;
40
41 // The last-seen time of this file to detect change.
42 base::Time last_seen;
43
44 // Once a file has been recognized as needing to be read, it is mapped into
45 // memory as a file ("active") or local memory ("atomic") and is assigned an
Alexei Svitkine (slow) 2016/02/19 16:57:00 This comment should explicitly mention |data| and
bcwhite 2016/02/19 19:50:15 Done.
46 // allocator.
47 std::vector<uint8_t> data;
48 scoped_ptr<base::MemoryMappedFile> mapped;
49 scoped_ptr<base::PersistentMemoryAllocator> allocator;
50
51 private:
52 DISALLOW_COPY_AND_ASSIGN(FileInfo);
53 };
54
55 FileMetricsProvider::FileMetricsProvider(
56 const scoped_refptr<base::TaskRunner>& task_runner,
57 PrefService* local_state)
58 : task_runner_(task_runner),
59 pref_service_(local_state),
60 weak_factory_(this) {
61 }
62
63 FileMetricsProvider::~FileMetricsProvider() {}
64
65 void FileMetricsProvider::RegisterFile(const base::FilePath& path,
66 FileType type,
67 const base::StringPiece prefs_key) {
68 scoped_ptr<FileInfo> file(new FileInfo());
69 file->path = path;
70 file->type = type;
71 file->prefs_key = prefs_key.as_string();
72
73 // |prefs_key| may be empty if the caller does not wish to persist the
74 // state across instances of the program.
75 if (pref_service_ && !prefs_key.empty()) {
76 file->last_seen = base::Time::FromInternalValue(
77 pref_service_->GetInt64(metrics::prefs::kMetricsLastSeenPrefix +
78 prefs_key.as_string()));
Alexei Svitkine (slow) 2016/02/19 16:57:00 Nit: Please cache prefs_key.as_string() as a local
bcwhite 2016/02/19 19:50:15 Even better, I can use file->prefs_key which is al
79 }
80
81 files_to_check_.push_back(std::move(file));
82 }
83
84 // static
85 void FileMetricsProvider::RegisterPrefs(PrefRegistrySimple* prefs,
86 const base::StringPiece prefs_key) {
87 prefs->RegisterInt64Pref(metrics::prefs::kMetricsLastSeenPrefix +
88 prefs_key.as_string(), 0);
89 }
90
91 // This method has all state information passed in |files| and is intended
92 // to run on a worker thread rather than the UI thread.
93 // static
94 void FileMetricsProvider::CheckAndMapNewMetricFilesOnTaskRunner(
95 FileMetricsProvider::FileInfoList* files) {
96 for (auto& file : *files) {
97 AccessResult result = CheckAndMapNewMetrics(file.get());
98 // Some results are not reported in order to keep the dashboard clean.
99 if (result != ACCESS_RESULT_DOESNT_EXIST &&
100 result != ACCESS_RESULT_NOT_MODIFIED) {
101 UMA_HISTOGRAM_ENUMERATION(
102 "UMA.FileMetricsProvider.AccessResult", result, ACCESS_RESULT_MAX);
103 }
104 }
105 }
106
107 // This method has all state information passed in |file| and is intended
108 // to run on a worker thread rather than the UI thread.
109 // static
110 FileMetricsProvider::AccessResult FileMetricsProvider::CheckAndMapNewMetrics(
111 FileMetricsProvider::FileInfo* file) {
112 DCHECK(!file->mapped);
113 DCHECK(file->data.empty());
114
115 base::File::Info info;
116 if (!base::GetFileInfo(file->path, &info))
117 return ACCESS_RESULT_DOESNT_EXIST;
118
119 if (info.is_directory || info.size == 0)
120 return ACCESS_RESULT_INVALID_FILE;
121
122 if (file->last_seen >= info.last_modified)
123 return ACCESS_RESULT_NOT_MODIFIED;
124
125 // A new file of metrics has been found. Map it into memory.
126 // TODO(bcwhite): Make this open read/write when supported for "active".
127 file->mapped.reset(new base::MemoryMappedFile());
128 if (!file->mapped->Initialize(file->path)) {
129 file->mapped.reset();
130 return ACCESS_RESULT_SYSTEM_MAP_FAILURE;
131 }
132
133 // Ensure any problems below don't occur repeatedly.
134 file->last_seen = info.last_modified;
135
136 // Test the validity of the file contents.
137 if (!base::FilePersistentMemoryAllocator::IsFileAcceptable(*file->mapped))
138 return ACCESS_RESULT_INVALID_CONTENTS;
139
140 // For an "atomic" file, immediately copy the data into local memory and
141 // release the file so that it is not held open.
142 if (file->type == FILE_HISTOGRAMS_ATOMIC) {
143 file->data.assign(file->mapped->data(),
144 file->mapped->data() + file->mapped->length());
145 file->mapped.reset();
146 }
147
148 return ACCESS_RESULT_SUCCESS;
149 }
150
151 void FileMetricsProvider::ScheduleFilesCheck() {
152 if (files_to_check_.empty())
153 return;
154
155 FileInfoList* check_list = new FileInfoList();
Alexei Svitkine (slow) 2016/02/19 16:57:00 Nit: I'd add a comment about where this will be fr
bcwhite 2016/02/19 19:50:15 Done.
156 std::swap(files_to_check_, *check_list);
157 task_runner_->PostTaskAndReply(
158 FROM_HERE,
159 base::Bind(&FileMetricsProvider::CheckAndMapNewMetricFilesOnTaskRunner,
160 base::Unretained(check_list)),
161 base::Bind(&FileMetricsProvider::RecordFilesChecked,
162 weak_factory_.GetWeakPtr(), base::Owned(check_list)));
163 }
164
165 void FileMetricsProvider::RecordHistogramSnapshotsFromFile(
166 base::HistogramSnapshotManager* snapshot_manager,
167 FileInfo* file) {
168 int histogram_count = 0;
Alexei Svitkine (slow) 2016/02/19 16:57:00 Nit: Move this to right above the while.
bcwhite 2016/02/19 19:50:15 Done.
169 base::PersistentMemoryAllocator::Iterator hist_iter;
170 file->allocator->CreateIterator(&hist_iter);
171
172 while (true) {
173 scoped_ptr<base::HistogramBase> histogram(
174 base::GetNextPersistentHistogram(file->allocator.get(), &hist_iter));
175 if (!histogram)
176 break;
177 if (file->type == FILE_HISTOGRAMS_ATOMIC)
178 snapshot_manager->PrepareAbsoluteTakingOwnership(std::move(histogram));
179 else
180 snapshot_manager->PrepareDeltaTakingOwnership(std::move(histogram));
181 ++histogram_count;
182 }
183
184 DVLOG(1) << "Reported " << histogram_count << " histograms from "
185 << file->path.value();
186 }
187
188 void FileMetricsProvider::CreateAllocatorForFile(FileInfo* file) {
189 DCHECK(!file->allocator);
190
191 // File data was validated earlier. Files are not considered "untrusted"
192 // as some processes might be (e.g. Renderer) so there's no need to check
193 // again to try to thwart some malicious actor that may have modified the
194 // data between then and now.
195 if (file->mapped) {
196 DCHECK(file->data.empty());
197 // TODO(bcwhite): Make this do read/write when supported for "active".
198 file->allocator.reset(new base::FilePersistentMemoryAllocator(
199 std::move(file->mapped), 0, std::string()));
200 } else {
201 DCHECK(!file->mapped);
202 file->allocator.reset(new base::PersistentMemoryAllocator(
203 &file->data[0], file->data.size(), 0, 0, "", true));
204 }
205 }
206
207 void FileMetricsProvider::RecordFilesChecked(FileInfoList* checked) {
208 DCHECK(thread_checker_.CalledOnValidThread());
Alexei Svitkine (slow) 2016/02/19 16:57:00 Nit: Can you add this to all the other methods in
bcwhite 2016/02/19 19:50:15 Done.
209
210 // Move each processed file to either the "to-read" list (for processing) or
211 // the "to-check" list (for future checking).
212 for (auto iter = checked->begin(); iter != checked->end();) {
213 auto temp = iter++;
214 const FileInfo* file = temp->get();
215 if (file->mapped || !file->data.empty())
216 files_to_read_.splice(files_to_read_.end(), *checked, temp);
217 else
218 files_to_check_.splice(files_to_check_.end(), *checked, temp);
219 }
220 }
221
222 void FileMetricsProvider::RecordFileAsSeen(FileInfo* file) {
223 if (pref_service_ && !file->prefs_key.empty()) {
224 pref_service_->SetInt64(metrics::prefs::kMetricsLastSeenPrefix +
225 file->prefs_key,
226 file->last_seen.ToInternalValue());
227 }
228 }
229
230 void FileMetricsProvider::OnDidCreateMetricsLog() {
231 DCHECK(thread_checker_.CalledOnValidThread());
232
233 // Move finished metric files back to list of monitored files.
234 for (auto iter = files_to_read_.begin(); iter != files_to_read_.end();) {
235 auto temp = iter++;
Alexei Svitkine (slow) 2016/02/19 16:57:00 This loop structure is pretty messy. There's no cl
bcwhite 2016/02/19 19:50:15 I can't say for sure how ":" iteration would deal
236 const FileInfo* file = temp->get();
237 if (!file->allocator && !file->mapped && file->data.empty())
238 files_to_check_.splice(files_to_check_.end(), files_to_read_, temp);
239 }
240
241 // Schedule a check to see if there are new metrics to load. If so, they
242 // will be reported during the next collection run after this one. The
243 // check is run off of the worker-pool so as to not cause delays on the
244 // main UI thread (which is currently where metric collection is done).
245 ScheduleFilesCheck();
246 }
247
248 void FileMetricsProvider::RecordHistogramSnapshots(
249 base::HistogramSnapshotManager* snapshot_manager) {
250 DCHECK(thread_checker_.CalledOnValidThread());
251
252 for (auto& file : files_to_read_) {
Alexei Svitkine (slow) 2016/02/19 16:57:00 Nit: (FileInfo* file : files_to_read_) Same in ot
bcwhite 2016/02/19 19:50:15 It'll have to be (scoped_ptr<FileInfo>& file : fil
253 // If the file is mapped or loaded then it needs to have an allocator
254 // attached to it in order to read histograms out of it.
255 if (file->mapped || !file->data.empty())
256 CreateAllocatorForFile(file.get());
257
258 // A file should not be under "files to read" unless it has an allocator
259 // or is memory-mapped (at which point it will have received an allocator
260 // above). However, if this method gets called twice before the scheduled-
261 // files-check has a chance to clean up, this may trigger. This also
262 // catches the case where creating an allocator from the file has failed.
263 if (!file->allocator)
264 continue;
265
266 // Dump all histograms contained within the file to the snapshot-manager.
267 RecordHistogramSnapshotsFromFile(snapshot_manager, file.get());
268
269 // Atomic files are read once and then ignored unless they change.
270 if (file->type == FILE_HISTOGRAMS_ATOMIC) {
271 DCHECK(!file->mapped);
272 file->allocator.reset();
273 file->data.clear();
274 RecordFileAsSeen(file.get());
275 }
276 }
277 }
278
279 } // namespace metrics
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698