Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / chromeos / system / statistics_provider.cc
1 // Copyright 2013 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 "chromeos/system/statistics_provider.h"
6
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/files/file_path.h"
10 #include "base/location.h"
11 #include "base/logging.h"
12 #include "base/memory/singleton.h"
13 #include "base/path_service.h"
14 #include "base/synchronization/cancellation_flag.h"
15 #include "base/synchronization/waitable_event.h"
16 #include "base/sys_info.h"
17 #include "base/task_runner.h"
18 #include "base/threading/thread_restrictions.h"
19 #include "base/time/time.h"
20 #include "chromeos/app_mode/kiosk_oem_manifest_parser.h"
21 #include "chromeos/chromeos_constants.h"
22 #include "chromeos/chromeos_switches.h"
23 #include "chromeos/system/name_value_pairs_parser.h"
24
25 namespace chromeos {
26 namespace system {
27
28 namespace {
29
30 // Path to the tool used to get system info, and delimiters for the output
31 // format of the tool.
32 const char* kCrosSystemTool[] = { "/usr/bin/crossystem" };
33 const char kCrosSystemEq[] = "=";
34 const char kCrosSystemDelim[] = "\n";
35 const char kCrosSystemCommentDelim[] = "#";
36 const char kCrosSystemUnknownValue[] = "(error)";
37
38 const char kHardwareClassCrosSystemKey[] = "hwid";
39 const char kUnknownHardwareClass[] = "unknown";
40
41 // File to get machine hardware info from, and key/value delimiters of
42 // the file.
43 // /tmp/machine-info is generated by platform/init/chromeos_startup.
44 const char kMachineHardwareInfoFile[] = "/tmp/machine-info";
45 const char kMachineHardwareInfoEq[] = "=";
46 const char kMachineHardwareInfoDelim[] = " \n";
47
48 // File to get ECHO coupon info from, and key/value delimiters of
49 // the file.
50 const char kEchoCouponFile[] = "/var/cache/echo/vpd_echo.txt";
51 const char kEchoCouponEq[] = "=";
52 const char kEchoCouponDelim[] = "\n";
53
54 // File to get VPD info from, and key/value delimiters of the file.
55 const char kVpdFile[] = "/var/log/vpd_2.0.txt";
56 const char kVpdEq[] = "=";
57 const char kVpdDelim[] = "\n";
58
59 // Timeout that we should wait for statistics to get loaded
60 const int kTimeoutSecs = 3;
61
62 // The location of OEM manifest file used to trigger OOBE flow for kiosk mode.
63 const CommandLine::CharType kOemManifestFilePath[] =
64     FILE_PATH_LITERAL("/usr/share/oem/oobe/manifest.json");
65
66 }  // namespace
67
68 // Key values for GetMachineStatistic()/GetMachineFlag() calls.
69 const char kDevSwitchBootMode[] = "devsw_boot";
70 const char kCustomizationIdKey[] = "customization_id";
71 const char kHardwareClassKey[] = "hardware_class";
72 const char kOffersCouponCodeKey[] = "ubind_attribute";
73 const char kOffersGroupCodeKey[] = "gbind_attribute";
74 const char kRlzBrandCodeKey[] = "rlz_brand_code";
75
76 // OEM specific statistics. Must be prefixed with "oem_".
77 const char kOemCanExitEnterpriseEnrollmentKey[] = "oem_can_exit_enrollment";
78 const char kOemDeviceRequisitionKey[] = "oem_device_requisition";
79 const char kOemIsEnterpriseManagedKey[] = "oem_enterprise_managed";
80 const char kOemKeyboardDrivenOobeKey[] = "oem_keyboard_driven_oobe";
81
82 bool HasOemPrefix(const std::string& name) {
83   return name.substr(0, 4) == "oem_";
84 }
85
86 // The StatisticsProvider implementation used in production.
87 class StatisticsProviderImpl : public StatisticsProvider {
88  public:
89   // StatisticsProvider implementation:
90   virtual void StartLoadingMachineStatistics(
91       const scoped_refptr<base::TaskRunner>& file_task_runner,
92       bool load_oem_manifest) OVERRIDE;
93   virtual bool GetMachineStatistic(const std::string& name,
94                                    std::string* result) OVERRIDE;
95   virtual bool GetMachineFlag(const std::string& name, bool* result) OVERRIDE;
96   virtual void Shutdown() OVERRIDE;
97
98   static StatisticsProviderImpl* GetInstance();
99
100  protected:
101   typedef std::map<std::string, bool> MachineFlags;
102   friend struct DefaultSingletonTraits<StatisticsProviderImpl>;
103
104   StatisticsProviderImpl();
105   virtual ~StatisticsProviderImpl();
106
107   // Waits up to |kTimeoutSecs| for statistics to be loaded. Returns true if
108   // they were loaded successfully.
109   bool WaitForStatisticsLoaded();
110
111   // Loads the machine statistics off of disk. Runs on the file thread.
112   void LoadMachineStatistics(bool load_oem_manifest);
113
114   // Loads the OEM statistics off of disk. Runs on the file thread.
115   void LoadOemManifestFromFile(const base::FilePath& file);
116
117   bool load_statistics_started_;
118   NameValuePairsParser::NameValueMap machine_info_;
119   MachineFlags machine_flags_;
120   base::CancellationFlag cancellation_flag_;
121   // |on_statistics_loaded_| protects |machine_info_| and |machine_flags_|.
122   base::WaitableEvent on_statistics_loaded_;
123   bool oem_manifest_loaded_;
124
125  private:
126   DISALLOW_COPY_AND_ASSIGN(StatisticsProviderImpl);
127 };
128
129 bool StatisticsProviderImpl::WaitForStatisticsLoaded() {
130   CHECK(load_statistics_started_);
131   if (on_statistics_loaded_.IsSignaled())
132     return true;
133
134   // Block if the statistics are not loaded yet. Normally this shouldn't
135   // happen excpet during OOBE.
136   base::Time start_time = base::Time::Now();
137   base::ThreadRestrictions::ScopedAllowWait allow_wait;
138   on_statistics_loaded_.TimedWait(base::TimeDelta::FromSeconds(kTimeoutSecs));
139
140   base::TimeDelta dtime = base::Time::Now() - start_time;
141   if (on_statistics_loaded_.IsSignaled()) {
142     LOG(ERROR) << "Statistics loaded after waiting "
143                << dtime.InMilliseconds() << "ms. ";
144     return true;
145   }
146
147   LOG(ERROR) << "Statistics not loaded after waiting "
148              << dtime.InMilliseconds() << "ms. ";
149   return false;
150 }
151
152 bool StatisticsProviderImpl::GetMachineStatistic(const std::string& name,
153                                                  std::string* result) {
154   VLOG(1) << "Machine Statistic requested: " << name;
155   if (!WaitForStatisticsLoaded()) {
156     LOG(ERROR) << "GetMachineStatistic called before load started: " << name;
157     return false;
158   }
159
160   NameValuePairsParser::NameValueMap::iterator iter = machine_info_.find(name);
161   if (iter == machine_info_.end()) {
162     if (base::SysInfo::IsRunningOnChromeOS() &&
163         (oem_manifest_loaded_ || !HasOemPrefix(name))) {
164       LOG(WARNING) << "Requested statistic not found: " << name;
165     }
166     return false;
167   }
168   *result = iter->second;
169   return true;
170 }
171
172 bool StatisticsProviderImpl::GetMachineFlag(const std::string& name,
173                                             bool* result) {
174   VLOG(1) << "Machine Flag requested: " << name;
175   if (!WaitForStatisticsLoaded()) {
176     LOG(ERROR) << "GetMachineFlag called before load started: " << name;
177     return false;
178   }
179
180   MachineFlags::const_iterator iter = machine_flags_.find(name);
181   if (iter == machine_flags_.end()) {
182     if (base::SysInfo::IsRunningOnChromeOS() &&
183         (oem_manifest_loaded_ || !HasOemPrefix(name))) {
184       LOG(WARNING) << "Requested machine flag not found: " << name;
185     }
186     return false;
187   }
188   *result = iter->second;
189   return true;
190 }
191
192 void StatisticsProviderImpl::Shutdown() {
193   cancellation_flag_.Set();  // Cancel any pending loads
194 }
195
196 StatisticsProviderImpl::StatisticsProviderImpl()
197     : load_statistics_started_(false),
198       on_statistics_loaded_(true  /* manual_reset */,
199                             false /* initially_signaled */),
200       oem_manifest_loaded_(false) {
201 }
202
203 StatisticsProviderImpl::~StatisticsProviderImpl() {
204 }
205
206 void StatisticsProviderImpl::StartLoadingMachineStatistics(
207     const scoped_refptr<base::TaskRunner>& file_task_runner,
208     bool load_oem_manifest) {
209   CHECK(!load_statistics_started_);
210   load_statistics_started_ = true;
211
212   VLOG(1) << "Started loading statistics. Load OEM Manifest: "
213           << load_oem_manifest;
214
215   file_task_runner->PostTask(
216       FROM_HERE,
217       base::Bind(&StatisticsProviderImpl::LoadMachineStatistics,
218                  base::Unretained(this),
219                  load_oem_manifest));
220 }
221
222 void StatisticsProviderImpl::LoadMachineStatistics(bool load_oem_manifest) {
223   // Run from the file task runner. StatisticsProviderImpl is a Singleton<> and
224   // will not be destroyed until after threads have been stopped, so this test
225   // is always safe.
226   if (cancellation_flag_.IsSet())
227     return;
228
229   NameValuePairsParser parser(&machine_info_);
230   if (base::SysInfo::IsRunningOnChromeOS()) {
231     // Parse all of the key/value pairs from the crossystem tool.
232     if (!parser.ParseNameValuePairsFromTool(arraysize(kCrosSystemTool),
233                                             kCrosSystemTool,
234                                             kCrosSystemEq,
235                                             kCrosSystemDelim,
236                                             kCrosSystemCommentDelim)) {
237       LOG(ERROR) << "Errors parsing output from: " << kCrosSystemTool;
238     }
239   }
240
241   parser.GetNameValuePairsFromFile(base::FilePath(kMachineHardwareInfoFile),
242                                    kMachineHardwareInfoEq,
243                                    kMachineHardwareInfoDelim);
244   parser.GetNameValuePairsFromFile(base::FilePath(kEchoCouponFile),
245                                    kEchoCouponEq,
246                                    kEchoCouponDelim);
247   parser.GetNameValuePairsFromFile(base::FilePath(kVpdFile),
248                                    kVpdEq,
249                                    kVpdDelim);
250
251   // Ensure that the hardware class key is present with the expected
252   // key name, and if it couldn't be retrieved, that the value is "unknown".
253   std::string hardware_class = machine_info_[kHardwareClassCrosSystemKey];
254   if (hardware_class.empty() || hardware_class == kCrosSystemUnknownValue)
255     machine_info_[kHardwareClassKey] = kUnknownHardwareClass;
256   else
257     machine_info_[kHardwareClassKey] = hardware_class;
258
259   if (load_oem_manifest) {
260     // If kAppOemManifestFile switch is specified, load OEM Manifest file.
261     CommandLine* command_line = CommandLine::ForCurrentProcess();
262     if (command_line->HasSwitch(switches::kAppOemManifestFile)) {
263       LoadOemManifestFromFile(
264           command_line->GetSwitchValuePath(switches::kAppOemManifestFile));
265     } else if (base::SysInfo::IsRunningOnChromeOS()) {
266       LoadOemManifestFromFile(base::FilePath(kOemManifestFilePath));
267     }
268     oem_manifest_loaded_ = true;
269   }
270
271   // Finished loading the statistics.
272   on_statistics_loaded_.Signal();
273   VLOG(1) << "Finished loading statistics.";
274 }
275
276 void StatisticsProviderImpl::LoadOemManifestFromFile(
277     const base::FilePath& file) {
278   // Called from LoadMachineStatistics. Check cancellation_flag_ again here.
279   if (cancellation_flag_.IsSet())
280     return;
281
282   KioskOemManifestParser::Manifest oem_manifest;
283   if (!KioskOemManifestParser::Load(file, &oem_manifest)) {
284     LOG(WARNING) << "Unable to load OEM Manifest file: " << file.value();
285     return;
286   }
287   machine_info_[kOemDeviceRequisitionKey] =
288       oem_manifest.device_requisition;
289   machine_flags_[kOemIsEnterpriseManagedKey] =
290       oem_manifest.enterprise_managed;
291   machine_flags_[kOemCanExitEnterpriseEnrollmentKey] =
292       oem_manifest.can_exit_enrollment;
293   machine_flags_[kOemKeyboardDrivenOobeKey] =
294       oem_manifest.keyboard_driven_oobe;
295
296   VLOG(1) << "Loaded OEM Manifest statistics from " << file.value();
297 }
298
299 StatisticsProviderImpl* StatisticsProviderImpl::GetInstance() {
300   return Singleton<StatisticsProviderImpl,
301                    DefaultSingletonTraits<StatisticsProviderImpl> >::get();
302 }
303
304 static StatisticsProvider* g_test_statistics_provider = NULL;
305
306 // static
307 StatisticsProvider* StatisticsProvider::GetInstance() {
308   if (g_test_statistics_provider)
309     return g_test_statistics_provider;
310   return StatisticsProviderImpl::GetInstance();
311 }
312
313 // static
314 void StatisticsProvider::SetTestProvider(StatisticsProvider* test_provider) {
315   g_test_statistics_provider = test_provider;
316 }
317
318 }  // namespace system
319 }  // namespace chromeos