blob: fe53955a25ed993b5ce4e48aaa6a7cb6b9e5fc18 [file] [log] [blame]
David Zeuthen27a48bc2013-08-06 12:06:29 -07001// Copyright (c) 2012 The Chromium OS 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
Alex Deymo8427b4a2014-11-05 14:00:32 -08005#include "update_engine/p2p_manager.h"
6
David Zeuthen27a48bc2013-08-06 12:06:29 -07007#include <glib.h>
8
David Zeuthen27a48bc2013-08-06 12:06:29 -07009#include <dirent.h>
Alex Vakulenko44cab302014-07-23 13:12:15 -070010#include <fcntl.h>
11#include <sys/stat.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070012#include <unistd.h>
Alex Vakulenko44cab302014-07-23 13:12:15 -070013#include <attr/xattr.h> // NOLINT - requires typed defined in unistd.h
David Zeuthen27a48bc2013-08-06 12:06:29 -070014
Ben Chan02f7c1d2014-10-18 15:18:02 -070015#include <memory>
16
Alex Deymo8427b4a2014-11-05 14:00:32 -080017#include <base/bind.h>
18#include <base/callback.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070019#include <base/strings/stringprintf.h>
Alex Deymo8427b4a2014-11-05 14:00:32 -080020#include <gmock/gmock.h>
21#include <gtest/gtest.h>
David Zeuthen92d9c8b2013-09-11 10:58:11 -070022#include <policy/libpolicy.h>
23#include <policy/mock_device_policy.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070024
David Zeuthen41f2cf52014-11-05 12:29:45 -050025#include "update_engine/fake_clock.h"
David Zeuthen27a48bc2013-08-06 12:06:29 -070026#include "update_engine/fake_p2p_manager_configuration.h"
27#include "update_engine/prefs.h"
28#include "update_engine/test_utils.h"
29#include "update_engine/utils.h"
30
Alex Deymof329b932014-10-30 01:37:48 -070031using base::TimeDelta;
David Zeuthen27a48bc2013-08-06 12:06:29 -070032using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070033using std::unique_ptr;
David Zeuthen27a48bc2013-08-06 12:06:29 -070034
35namespace chromeos_update_engine {
36
37// Test fixture that sets up a testing configuration (with e.g. a
38// temporary p2p dir) for P2PManager and cleans up when the test is
39// done.
40class P2PManagerTest : public testing::Test {
Alex Vakulenkod2779df2014-06-16 13:19:00 -070041 protected:
David Zeuthen27a48bc2013-08-06 12:06:29 -070042 P2PManagerTest() {}
43 virtual ~P2PManagerTest() {}
44
45 // Derived from testing::Test.
46 virtual void SetUp() {
47 test_conf_ = new FakeP2PManagerConfiguration();
48 }
49 virtual void TearDown() {}
50
51 // The P2PManager::Configuration instance used for testing.
52 FakeP2PManagerConfiguration *test_conf_;
53};
54
55
David Zeuthen92d9c8b2013-09-11 10:58:11 -070056// Check that IsP2PEnabled() returns false if neither the crosh flag
57// nor the Enterprise Policy indicates p2p is to be used.
58TEST_F(P2PManagerTest, P2PEnabledNeitherCroshFlagNotEnterpriseSetting) {
David Zeuthen27a48bc2013-08-06 12:06:29 -070059 string temp_dir;
60 Prefs prefs;
Gilad Arnolda6742b32014-01-11 00:18:34 -080061 EXPECT_TRUE(utils::MakeTempDirectory("PayloadStateP2PTests.XXXXXX",
David Zeuthen27a48bc2013-08-06 12:06:29 -070062 &temp_dir));
Alex Vakulenko75039d72014-03-25 12:36:28 -070063 prefs.Init(base::FilePath(temp_dir));
David Zeuthen27a48bc2013-08-06 12:06:29 -070064
David Zeuthen41f2cf52014-11-05 12:29:45 -050065 unique_ptr<P2PManager> manager(P2PManager::Construct(
66 test_conf_, &prefs, nullptr, "cros_au", 3,
67 base::TimeDelta::FromDays(5)));
David Zeuthen27a48bc2013-08-06 12:06:29 -070068 EXPECT_FALSE(manager->IsP2PEnabled());
David Zeuthen92d9c8b2013-09-11 10:58:11 -070069
70 EXPECT_TRUE(utils::RecursiveUnlinkDir(temp_dir));
71}
72
73// Check that IsP2PEnabled() corresponds to value of the crosh flag
74// when Enterprise Policy is not set.
75TEST_F(P2PManagerTest, P2PEnabledCroshFlag) {
76 string temp_dir;
77 Prefs prefs;
Gilad Arnolda6742b32014-01-11 00:18:34 -080078 EXPECT_TRUE(utils::MakeTempDirectory("PayloadStateP2PTests.XXXXXX",
David Zeuthen92d9c8b2013-09-11 10:58:11 -070079 &temp_dir));
Alex Vakulenko75039d72014-03-25 12:36:28 -070080 prefs.Init(base::FilePath(temp_dir));
David Zeuthen92d9c8b2013-09-11 10:58:11 -070081
David Zeuthen41f2cf52014-11-05 12:29:45 -050082 unique_ptr<P2PManager> manager(P2PManager::Construct(
83 test_conf_, &prefs, nullptr, "cros_au", 3,
84 base::TimeDelta::FromDays(5)));
David Zeuthen92d9c8b2013-09-11 10:58:11 -070085 EXPECT_FALSE(manager->IsP2PEnabled());
86 prefs.SetBoolean(kPrefsP2PEnabled, true);
87 EXPECT_TRUE(manager->IsP2PEnabled());
88 prefs.SetBoolean(kPrefsP2PEnabled, false);
89 EXPECT_FALSE(manager->IsP2PEnabled());
90
91 EXPECT_TRUE(utils::RecursiveUnlinkDir(temp_dir));
92}
93
94// Check that IsP2PEnabled() always returns true if Enterprise Policy
95// indicates that p2p is to be used.
96TEST_F(P2PManagerTest, P2PEnabledEnterpriseSettingTrue) {
97 string temp_dir;
98 Prefs prefs;
Gilad Arnolda6742b32014-01-11 00:18:34 -080099 EXPECT_TRUE(utils::MakeTempDirectory("PayloadStateP2PTests.XXXXXX",
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700100 &temp_dir));
Alex Vakulenko75039d72014-03-25 12:36:28 -0700101 prefs.Init(base::FilePath(temp_dir));
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700102
David Zeuthen41f2cf52014-11-05 12:29:45 -0500103 unique_ptr<P2PManager> manager(P2PManager::Construct(
104 test_conf_, &prefs, nullptr, "cros_au", 3,
105 base::TimeDelta::FromDays(5)));
Ben Chan02f7c1d2014-10-18 15:18:02 -0700106 unique_ptr<policy::MockDevicePolicy> device_policy(
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700107 new policy::MockDevicePolicy());
108 EXPECT_CALL(*device_policy, GetAuP2PEnabled(testing::_)).WillRepeatedly(
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700109 DoAll(testing::SetArgumentPointee<0>(true),
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700110 testing::Return(true)));
111 manager->SetDevicePolicy(device_policy.get());
112 EXPECT_TRUE(manager->IsP2PEnabled());
113
114 // Should still return true even if crosh flag says otherwise.
115 prefs.SetBoolean(kPrefsP2PEnabled, false);
116 EXPECT_TRUE(manager->IsP2PEnabled());
117
118 EXPECT_TRUE(utils::RecursiveUnlinkDir(temp_dir));
119}
120
Alex Vakulenko072359c2014-07-18 11:41:07 -0700121// Check that IsP2PEnabled() corresponds to the value of the crosh
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700122// flag if Enterprise Policy indicates that p2p is not to be used.
123TEST_F(P2PManagerTest, P2PEnabledEnterpriseSettingFalse) {
124 string temp_dir;
125 Prefs prefs;
Gilad Arnolda6742b32014-01-11 00:18:34 -0800126 EXPECT_TRUE(utils::MakeTempDirectory("PayloadStateP2PTests.XXXXXX",
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700127 &temp_dir));
Alex Vakulenko75039d72014-03-25 12:36:28 -0700128 prefs.Init(base::FilePath(temp_dir));
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700129
David Zeuthen41f2cf52014-11-05 12:29:45 -0500130 unique_ptr<P2PManager> manager(P2PManager::Construct(
131 test_conf_, &prefs, nullptr, "cros_au", 3,
132 base::TimeDelta::FromDays(5)));
Ben Chan02f7c1d2014-10-18 15:18:02 -0700133 unique_ptr<policy::MockDevicePolicy> device_policy(
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700134 new policy::MockDevicePolicy());
135 EXPECT_CALL(*device_policy, GetAuP2PEnabled(testing::_)).WillRepeatedly(
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700136 DoAll(testing::SetArgumentPointee<0>(false),
David Zeuthen92d9c8b2013-09-11 10:58:11 -0700137 testing::Return(true)));
138 manager->SetDevicePolicy(device_policy.get());
139 EXPECT_FALSE(manager->IsP2PEnabled());
140
David Zeuthen27a48bc2013-08-06 12:06:29 -0700141 prefs.SetBoolean(kPrefsP2PEnabled, true);
142 EXPECT_TRUE(manager->IsP2PEnabled());
143 prefs.SetBoolean(kPrefsP2PEnabled, false);
144 EXPECT_FALSE(manager->IsP2PEnabled());
145
146 EXPECT_TRUE(utils::RecursiveUnlinkDir(temp_dir));
147}
148
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400149// Check that IsP2PEnabled() returns TRUE if
150// - The crosh flag is not set.
151// - Enterprise Policy is not set.
152// - Device is Enterprise Enrolled.
153TEST_F(P2PManagerTest, P2PEnabledEnterpriseEnrolledDevicesDefaultToEnabled) {
154 string temp_dir;
155 Prefs prefs;
156 EXPECT_TRUE(utils::MakeTempDirectory("PayloadStateP2PTests.XXXXXX",
157 &temp_dir));
158 prefs.Init(base::FilePath(temp_dir));
159
David Zeuthen41f2cf52014-11-05 12:29:45 -0500160 unique_ptr<P2PManager> manager(P2PManager::Construct(
161 test_conf_, &prefs, nullptr, "cros_au", 3,
162 base::TimeDelta::FromDays(5)));
Ben Chan02f7c1d2014-10-18 15:18:02 -0700163 unique_ptr<policy::MockDevicePolicy> device_policy(
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400164 new policy::MockDevicePolicy());
165 // We return an empty owner as this is an enterprise.
166 EXPECT_CALL(*device_policy, GetOwner(testing::_)).WillRepeatedly(
Alex Deymof329b932014-10-30 01:37:48 -0700167 DoAll(testing::SetArgumentPointee<0>(string("")),
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400168 testing::Return(true)));
169 manager->SetDevicePolicy(device_policy.get());
170 EXPECT_TRUE(manager->IsP2PEnabled());
171
172 EXPECT_TRUE(utils::RecursiveUnlinkDir(temp_dir));
173}
174
175// Check that IsP2PEnabled() returns FALSE if
176// - The crosh flag is not set.
177// - Enterprise Policy is set to FALSE.
178// - Device is Enterprise Enrolled.
179TEST_F(P2PManagerTest, P2PEnabledEnterpriseEnrolledDevicesOverrideDefault) {
180 string temp_dir;
181 Prefs prefs;
182 EXPECT_TRUE(utils::MakeTempDirectory("PayloadStateP2PTests.XXXXXX",
183 &temp_dir));
184 prefs.Init(base::FilePath(temp_dir));
185
David Zeuthen41f2cf52014-11-05 12:29:45 -0500186 unique_ptr<P2PManager> manager(P2PManager::Construct(
187 test_conf_, &prefs, nullptr, "cros_au", 3,
188 base::TimeDelta::FromDays(5)));
Ben Chan02f7c1d2014-10-18 15:18:02 -0700189 unique_ptr<policy::MockDevicePolicy> device_policy(
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400190 new policy::MockDevicePolicy());
191 // We return an empty owner as this is an enterprise.
192 EXPECT_CALL(*device_policy, GetOwner(testing::_)).WillRepeatedly(
Alex Deymof329b932014-10-30 01:37:48 -0700193 DoAll(testing::SetArgumentPointee<0>(string("")),
David Zeuthen9a58e6a2014-09-22 17:38:44 -0400194 testing::Return(true)));
195 // Make Enterprise Policy indicate p2p is not enabled.
196 EXPECT_CALL(*device_policy, GetAuP2PEnabled(testing::_)).WillRepeatedly(
197 DoAll(testing::SetArgumentPointee<0>(false),
198 testing::Return(true)));
199 manager->SetDevicePolicy(device_policy.get());
200 EXPECT_FALSE(manager->IsP2PEnabled());
201
202 EXPECT_TRUE(utils::RecursiveUnlinkDir(temp_dir));
203}
204
David Zeuthen27a48bc2013-08-06 12:06:29 -0700205// Check that we keep the $N newest files with the .$EXT.p2p extension.
David Zeuthen41f2cf52014-11-05 12:29:45 -0500206TEST_F(P2PManagerTest, HousekeepingCountLimit) {
207 // Specifically pass 0 for |max_file_age| to allow files of any age.
208 unique_ptr<P2PManager> manager(P2PManager::Construct(
209 test_conf_, nullptr, nullptr, "cros_au", 3,
210 base::TimeDelta() /* max_file_age */));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700211 EXPECT_EQ(manager->CountSharedFiles(), 0);
212
Alex Deymo0f513512013-09-13 14:11:26 -0700213 // Generate files with different timestamps matching our pattern and generate
214 // other files not matching the pattern.
215 double last_timestamp = -1;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700216 for (int n = 0; n < 5; n++) {
Alex Deymo0f513512013-09-13 14:11:26 -0700217 double current_timestamp;
218 do {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700219 base::FilePath file = test_conf_->GetP2PDir().Append(base::StringPrintf(
Alex Deymo0f513512013-09-13 14:11:26 -0700220 "file_%d.cros_au.p2p", n));
Alex Vakulenko75039d72014-03-25 12:36:28 -0700221 EXPECT_EQ(0, System(base::StringPrintf("touch %s",
222 file.value().c_str())));
David Zeuthen45e2ae22013-09-03 11:46:11 -0700223
Alex Deymo0f513512013-09-13 14:11:26 -0700224 // Check that the current timestamp on the file is different from the
225 // previous generated file. This timestamp depends on the file system
226 // time resolution, for example, ext2/ext3 have a time resolution of one
227 // second while ext4 has a resolution of one nanosecond. If the assigned
228 // timestamp is the same, we introduce a bigger sleep and call touch
229 // again.
230 struct stat statbuf;
231 EXPECT_EQ(stat(file.value().c_str(), &statbuf), 0);
232 current_timestamp = utils::TimeFromStructTimespec(&statbuf.st_ctim)
233 .ToDoubleT();
234 if (current_timestamp == last_timestamp)
235 sleep(1);
236 } while (current_timestamp == last_timestamp);
237 last_timestamp = current_timestamp;
238
Alex Vakulenko75039d72014-03-25 12:36:28 -0700239 EXPECT_EQ(0, System(base::StringPrintf(
240 "touch %s/file_%d.OTHER.p2p",
241 test_conf_->GetP2PDir().value().c_str(), n)));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700242
Alex Deymo0f513512013-09-13 14:11:26 -0700243 // A sleep of one micro-second is enough to have a different "Change" time
244 // on the file on newer file systems.
245 g_usleep(1);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700246 }
247 // CountSharedFiles() only counts 'cros_au' files.
248 EXPECT_EQ(manager->CountSharedFiles(), 5);
249
250 EXPECT_TRUE(manager->PerformHousekeeping());
251
252 // At this point - after HouseKeeping - we should only have
253 // eight files left.
254 for (int n = 0; n < 5; n++) {
255 string file_name;
256 bool expect;
257
258 expect = (n >= 2);
Alex Vakulenko75039d72014-03-25 12:36:28 -0700259 file_name = base::StringPrintf(
260 "%s/file_%d.cros_au.p2p",
261 test_conf_->GetP2PDir().value().c_str(), n);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700262 EXPECT_EQ(!!g_file_test(file_name.c_str(), G_FILE_TEST_EXISTS), expect);
263
Alex Vakulenko75039d72014-03-25 12:36:28 -0700264 file_name = base::StringPrintf(
265 "%s/file_%d.OTHER.p2p",
266 test_conf_->GetP2PDir().value().c_str(), n);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700267 EXPECT_TRUE(g_file_test(file_name.c_str(), G_FILE_TEST_EXISTS));
268 }
269 // CountSharedFiles() only counts 'cros_au' files.
270 EXPECT_EQ(manager->CountSharedFiles(), 3);
271}
272
David Zeuthen41f2cf52014-11-05 12:29:45 -0500273// Check that we keep files with the .$EXT.p2p extension not older
274// than some specificed age (5 days, in this test).
275TEST_F(P2PManagerTest, HousekeepingAgeLimit) {
276 // We set the cutoff time to be 1 billion seconds (01:46:40 UTC on 9
277 // September 2001 - arbitrary number, but constant to avoid test
278 // flakiness) since the epoch and then we put two files before that
279 // date and three files after.
280 time_t cutoff_time = 1000000000;
281 base::TimeDelta age_limit = base::TimeDelta::FromDays(5);
282
283 // Set the clock just so files with a timestamp before |cutoff_time|
284 // will be deleted at housekeeping.
285 FakeClock fake_clock;
286 fake_clock.SetWallclockTime(base::Time::FromTimeT(cutoff_time) + age_limit);
287
288 // Specifically pass 0 for |num_files_to_keep| to allow files of any age.
289 unique_ptr<P2PManager> manager(P2PManager::Construct(
290 test_conf_, nullptr, &fake_clock, "cros_au",
291 0 /* num_files_to_keep */, age_limit));
292 EXPECT_EQ(manager->CountSharedFiles(), 0);
293
294 // Generate files with different timestamps matching our pattern and generate
295 // other files not matching the pattern.
296 for (int n = 0; n < 5; n++) {
297 base::FilePath file = test_conf_->GetP2PDir().Append(base::StringPrintf(
298 "file_%d.cros_au.p2p", n));
299
300 // With five files and aiming for two of them to be before
301 // |cutoff_time|, we distribute it like this:
302 //
303 // -------- 0 -------- 1 -------- 2 -------- 3 -------- 4 --------
304 // |
305 // cutoff_time
306 //
307 base::Time file_date = base::Time::FromTimeT(cutoff_time) +
308 (n - 2)*base::TimeDelta::FromDays(1) + base::TimeDelta::FromHours(12);
309
310 // The touch(1) command expects input like this
311 // --date="2004-02-27 14:19:13.489392193 +0530"
312 base::Time::Exploded exploded;
313 file_date.UTCExplode(&exploded);
314 string file_date_string = base::StringPrintf(
315 "%d-%02d-%02d %02d:%02d:%02d +0000",
316 exploded.year, exploded.month, exploded.day_of_month,
317 exploded.hour, exploded.minute, exploded.second);
318
319 // Sanity check that we generated the correct string.
320 base::Time parsed_time;
321 EXPECT_TRUE(base::Time::FromUTCString(file_date_string.c_str(),
322 &parsed_time));
323 EXPECT_EQ(parsed_time, file_date);
324
325 EXPECT_EQ(0, System(base::StringPrintf("touch --date=\"%s\" %s",
326 file_date_string.c_str(),
327 file.value().c_str())));
328
329 EXPECT_EQ(0, System(base::StringPrintf(
330 "touch --date=\"%s\" %s/file_%d.OTHER.p2p",
331 file_date_string.c_str(),
332 test_conf_->GetP2PDir().value().c_str(), n)));
333 }
334 // CountSharedFiles() only counts 'cros_au' files.
335 EXPECT_EQ(manager->CountSharedFiles(), 5);
336
337 EXPECT_TRUE(manager->PerformHousekeeping());
338
339 // At this point - after HouseKeeping - we should only have
340 // eight files left.
341 for (int n = 0; n < 5; n++) {
342 string file_name;
343 bool expect;
344
345 expect = (n >= 2);
346 file_name = base::StringPrintf(
347 "%s/file_%d.cros_au.p2p",
348 test_conf_->GetP2PDir().value().c_str(), n);
349 EXPECT_EQ(!!g_file_test(file_name.c_str(), G_FILE_TEST_EXISTS), expect);
350
351 file_name = base::StringPrintf(
352 "%s/file_%d.OTHER.p2p",
353 test_conf_->GetP2PDir().value().c_str(), n);
354 EXPECT_TRUE(g_file_test(file_name.c_str(), G_FILE_TEST_EXISTS));
355 }
356 // CountSharedFiles() only counts 'cros_au' files.
357 EXPECT_EQ(manager->CountSharedFiles(), 3);
358}
359
David Zeuthen27a48bc2013-08-06 12:06:29 -0700360static bool CheckP2PFile(const string& p2p_dir, const string& file_name,
361 ssize_t expected_size, ssize_t expected_size_xattr) {
362 string path = p2p_dir + "/" + file_name;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700363 char ea_value[64] = { 0 };
364 ssize_t ea_size;
365
Gabe Blacka77939e2014-09-09 23:35:08 -0700366 off_t p2p_size = utils::FileSize(path);
367 if (p2p_size < 0) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700368 LOG(ERROR) << "File " << path << " does not exist";
369 return false;
370 }
371
372 if (expected_size != 0) {
Gabe Blacka77939e2014-09-09 23:35:08 -0700373 if (p2p_size != expected_size) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700374 LOG(ERROR) << "Expected size " << expected_size
Gabe Blacka77939e2014-09-09 23:35:08 -0700375 << " but size was " << p2p_size;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700376 return false;
377 }
378 }
379
380 if (expected_size_xattr == 0) {
381 ea_size = getxattr(path.c_str(), "user.cros-p2p-filesize",
382 &ea_value, sizeof ea_value - 1);
383 if (ea_size == -1 && errno == ENOATTR) {
384 // This is valid behavior as we support files without the xattr set.
385 } else {
386 PLOG(ERROR) << "getxattr() didn't fail with ENOATTR as expected, "
387 << "ea_size=" << ea_size << ", errno=" << errno;
388 return false;
389 }
390 } else {
391 ea_size = getxattr(path.c_str(), "user.cros-p2p-filesize",
392 &ea_value, sizeof ea_value - 1);
393 if (ea_size < 0) {
394 LOG(ERROR) << "Error getting xattr attribute";
395 return false;
396 }
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700397 char* endp = nullptr;
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700398 long long int val = strtoll(ea_value, &endp, 0); // NOLINT(runtime/int)
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700399 if (endp == nullptr || *endp != '\0') {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700400 LOG(ERROR) << "Error parsing xattr '" << ea_value
401 << "' as an integer";
402 return false;
403 }
404 if (val != expected_size_xattr) {
405 LOG(ERROR) << "Expected xattr size " << expected_size_xattr
406 << " but size was " << val;
407 return false;
408 }
409 }
410
411 return true;
412}
413
414static bool CreateP2PFile(string p2p_dir, string file_name,
415 size_t size, size_t size_xattr) {
416 string path = p2p_dir + "/" + file_name;
417
418 int fd = open(path.c_str(), O_CREAT|O_RDWR, 0644);
419 if (fd == -1) {
420 PLOG(ERROR) << "Error creating file with path " << path;
421 return false;
422 }
423 if (ftruncate(fd, size) != 0) {
424 PLOG(ERROR) << "Error truncating " << path << " to size " << size;
425 close(fd);
426 return false;
427 }
428
429 if (size_xattr != 0) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700430 string decimal_size = base::StringPrintf("%zu", size_xattr);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700431 if (fsetxattr(fd, "user.cros-p2p-filesize",
432 decimal_size.c_str(), decimal_size.size(), 0) != 0) {
433 PLOG(ERROR) << "Error setting xattr on " << path;
434 close(fd);
435 return false;
436 }
437 }
438
439 close(fd);
440 return true;
441}
442
443// Check that sharing a *new* file works.
444TEST_F(P2PManagerTest, ShareFile) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700445 if (!utils::IsXAttrSupported(base::FilePath("/tmp"))) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700446 LOG(WARNING) << "Skipping test because /tmp does not support xattr. "
447 << "Please update your system to support this feature.";
448 return;
449 }
450
David Zeuthen41f2cf52014-11-05 12:29:45 -0500451 unique_ptr<P2PManager> manager(P2PManager::Construct(
452 test_conf_, nullptr, nullptr, "cros_au", 3,
453 base::TimeDelta::FromDays(5)));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700454 EXPECT_TRUE(manager->FileShare("foo", 10 * 1000 * 1000));
455 EXPECT_EQ(manager->FileGetPath("foo"),
456 test_conf_->GetP2PDir().Append("foo.cros_au.p2p.tmp"));
457 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
458 "foo.cros_au.p2p.tmp", 0, 10 * 1000 * 1000));
459
460 // Sharing it again - with the same expected size - should return true
461 EXPECT_TRUE(manager->FileShare("foo", 10 * 1000 * 1000));
462
463 // ... but if we use the wrong size, it should fail
464 EXPECT_FALSE(manager->FileShare("foo", 10 * 1000 * 1000 + 1));
465}
466
467// Check that making a shared file visible, does what is expected.
468TEST_F(P2PManagerTest, MakeFileVisible) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700469 if (!utils::IsXAttrSupported(base::FilePath("/tmp"))) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700470 LOG(WARNING) << "Skipping test because /tmp does not support xattr. "
471 << "Please update your system to support this feature.";
472 return;
473 }
474
David Zeuthen41f2cf52014-11-05 12:29:45 -0500475 unique_ptr<P2PManager> manager(P2PManager::Construct(
476 test_conf_, nullptr, nullptr, "cros_au", 3,
477 base::TimeDelta::FromDays(5)));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700478 // First, check that it's not visible.
479 manager->FileShare("foo", 10*1000*1000);
480 EXPECT_EQ(manager->FileGetPath("foo"),
481 test_conf_->GetP2PDir().Append("foo.cros_au.p2p.tmp"));
482 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
483 "foo.cros_au.p2p.tmp", 0, 10 * 1000 * 1000));
484 // Make the file visible and check that it changed its name. Do it
485 // twice to check that FileMakeVisible() is idempotent.
486 for (int n = 0; n < 2; n++) {
487 manager->FileMakeVisible("foo");
488 EXPECT_EQ(manager->FileGetPath("foo"),
489 test_conf_->GetP2PDir().Append("foo.cros_au.p2p"));
490 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
491 "foo.cros_au.p2p", 0, 10 * 1000 * 1000));
492 }
493}
494
495// Check that we return the right values for existing files in P2P_DIR.
496TEST_F(P2PManagerTest, ExistingFiles) {
Alex Vakulenko75039d72014-03-25 12:36:28 -0700497 if (!utils::IsXAttrSupported(base::FilePath("/tmp"))) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700498 LOG(WARNING) << "Skipping test because /tmp does not support xattr. "
499 << "Please update your system to support this feature.";
500 return;
501 }
502
David Zeuthen41f2cf52014-11-05 12:29:45 -0500503 unique_ptr<P2PManager> manager(P2PManager::Construct(
504 test_conf_, nullptr, nullptr, "cros_au", 3,
505 base::TimeDelta::FromDays(5)));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700506 bool visible;
507
508 // Check that errors are returned if the file does not exist
Alex Vakulenko75039d72014-03-25 12:36:28 -0700509 EXPECT_EQ(manager->FileGetPath("foo"), base::FilePath());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700510 EXPECT_EQ(manager->FileGetSize("foo"), -1);
511 EXPECT_EQ(manager->FileGetExpectedSize("foo"), -1);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700512 EXPECT_FALSE(manager->FileGetVisible("foo", nullptr));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700513 // ... then create the file ...
514 EXPECT_TRUE(CreateP2PFile(test_conf_->GetP2PDir().value(),
515 "foo.cros_au.p2p", 42, 43));
516 // ... and then check that the expected values are returned
517 EXPECT_EQ(manager->FileGetPath("foo"),
518 test_conf_->GetP2PDir().Append("foo.cros_au.p2p"));
519 EXPECT_EQ(manager->FileGetSize("foo"), 42);
520 EXPECT_EQ(manager->FileGetExpectedSize("foo"), 43);
521 EXPECT_TRUE(manager->FileGetVisible("foo", &visible));
522 EXPECT_TRUE(visible);
523
524 // One more time, this time with a .tmp variant. First ensure it errors out..
Alex Vakulenko75039d72014-03-25 12:36:28 -0700525 EXPECT_EQ(manager->FileGetPath("bar"), base::FilePath());
David Zeuthen27a48bc2013-08-06 12:06:29 -0700526 EXPECT_EQ(manager->FileGetSize("bar"), -1);
527 EXPECT_EQ(manager->FileGetExpectedSize("bar"), -1);
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700528 EXPECT_FALSE(manager->FileGetVisible("bar", nullptr));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700529 // ... then create the file ...
530 EXPECT_TRUE(CreateP2PFile(test_conf_->GetP2PDir().value(),
531 "bar.cros_au.p2p.tmp", 44, 45));
532 // ... and then check that the expected values are returned
533 EXPECT_EQ(manager->FileGetPath("bar"),
534 test_conf_->GetP2PDir().Append("bar.cros_au.p2p.tmp"));
535 EXPECT_EQ(manager->FileGetSize("bar"), 44);
536 EXPECT_EQ(manager->FileGetExpectedSize("bar"), 45);
537 EXPECT_TRUE(manager->FileGetVisible("bar", &visible));
538 EXPECT_FALSE(visible);
539}
540
David Zeuthen27a48bc2013-08-06 12:06:29 -0700541// This is a little bit ugly but short of mocking a 'p2p' service this
542// will have to do. E.g. we essentially simulate the various
543// behaviours of initctl(8) that we rely on.
544TEST_F(P2PManagerTest, StartP2P) {
David Zeuthen41f2cf52014-11-05 12:29:45 -0500545 unique_ptr<P2PManager> manager(P2PManager::Construct(
546 test_conf_, nullptr, nullptr, "cros_au", 3,
547 base::TimeDelta::FromDays(5)));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700548
549 // Check that we can start the service
550 test_conf_->SetInitctlStartCommandLine("true");
551 EXPECT_TRUE(manager->EnsureP2PRunning());
552 test_conf_->SetInitctlStartCommandLine("false");
553 EXPECT_FALSE(manager->EnsureP2PRunning());
554 test_conf_->SetInitctlStartCommandLine(
555 "sh -c 'echo \"initctl: Job is already running: p2p\" >&2; false'");
556 EXPECT_TRUE(manager->EnsureP2PRunning());
557 test_conf_->SetInitctlStartCommandLine(
558 "sh -c 'echo something else >&2; false'");
559 EXPECT_FALSE(manager->EnsureP2PRunning());
560}
561
562// Same comment as for StartP2P
563TEST_F(P2PManagerTest, StopP2P) {
David Zeuthen41f2cf52014-11-05 12:29:45 -0500564 unique_ptr<P2PManager> manager(P2PManager::Construct(
565 test_conf_, nullptr, nullptr, "cros_au", 3,
566 base::TimeDelta::FromDays(5)));
David Zeuthen27a48bc2013-08-06 12:06:29 -0700567
568 // Check that we can start the service
569 test_conf_->SetInitctlStopCommandLine("true");
570 EXPECT_TRUE(manager->EnsureP2PNotRunning());
571 test_conf_->SetInitctlStopCommandLine("false");
572 EXPECT_FALSE(manager->EnsureP2PNotRunning());
573 test_conf_->SetInitctlStopCommandLine(
574 "sh -c 'echo \"initctl: Unknown instance \" >&2; false'");
575 EXPECT_TRUE(manager->EnsureP2PNotRunning());
576 test_conf_->SetInitctlStopCommandLine(
577 "sh -c 'echo something else >&2; false'");
578 EXPECT_FALSE(manager->EnsureP2PNotRunning());
579}
580
581static void ExpectUrl(const string& expected_url,
582 GMainLoop* loop,
583 const string& url) {
584 EXPECT_EQ(url, expected_url);
585 g_main_loop_quit(loop);
586}
587
588// Like StartP2P, we're mocking the different results that p2p-client
589// can return. It's not pretty but it works.
590TEST_F(P2PManagerTest, LookupURL) {
David Zeuthen41f2cf52014-11-05 12:29:45 -0500591 unique_ptr<P2PManager> manager(P2PManager::Construct(
592 test_conf_, nullptr, nullptr, "cros_au", 3,
593 base::TimeDelta::FromDays(5)));
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700594 GMainLoop *loop = g_main_loop_new(nullptr, FALSE);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700595
596 // Emulate p2p-client returning valid URL with "fooX", 42 and "cros_au"
597 // being propagated in the right places.
Alex Deymo8ad6da92014-07-15 17:17:45 -0700598 test_conf_->SetP2PClientCommandLine(
599 "echo 'http://1.2.3.4/{file_id}_{minsize}'");
David Zeuthen27a48bc2013-08-06 12:06:29 -0700600 manager->LookupUrlForFile("fooX", 42, TimeDelta(),
601 base::Bind(ExpectUrl,
602 "http://1.2.3.4/fooX.cros_au_42", loop));
603 g_main_loop_run(loop);
604
605 // Emulate p2p-client returning invalid URL.
606 test_conf_->SetP2PClientCommandLine("echo 'not_a_valid_url'");
607 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
608 base::Bind(ExpectUrl, "", loop));
609 g_main_loop_run(loop);
610
611 // Emulate p2p-client conveying failure.
612 test_conf_->SetP2PClientCommandLine("false");
613 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
614 base::Bind(ExpectUrl, "", loop));
615 g_main_loop_run(loop);
616
617 // Emulate p2p-client not existing.
618 test_conf_->SetP2PClientCommandLine("/path/to/non/existent/helper/program");
619 manager->LookupUrlForFile("foobar", 42,
620 TimeDelta(),
621 base::Bind(ExpectUrl, "", loop));
622 g_main_loop_run(loop);
623
624 // Emulate p2p-client crashing.
625 test_conf_->SetP2PClientCommandLine("sh -c 'kill -SEGV $$'");
626 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
627 base::Bind(ExpectUrl, "", loop));
628 g_main_loop_run(loop);
629
630 // Emulate p2p-client exceeding its timeout.
631 test_conf_->SetP2PClientCommandLine("sh -c 'echo http://1.2.3.4/; sleep 2'");
632 manager->LookupUrlForFile("foobar", 42, TimeDelta::FromMilliseconds(500),
633 base::Bind(ExpectUrl, "", loop));
634 g_main_loop_run(loop);
635
636 g_main_loop_unref(loop);
637}
638
Alex Vakulenkod2779df2014-06-16 13:19:00 -0700639} // namespace chromeos_update_engine