blob: bee0248194b0643aca5220a8875305ca8d511eff [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
5#include <glib.h>
6
7#include <sys/stat.h>
8#include <fcntl.h>
9#include <dirent.h>
10#include <unistd.h>
11#include <attr/xattr.h>
12
13#include "gmock/gmock.h"
14#include "gtest/gtest.h"
15
16#include "base/bind.h"
17#include "base/callback.h"
18#include "base/stringprintf.h"
David Zeuthen92d9c8b2013-09-11 10:58:11 -070019#include <policy/libpolicy.h>
20#include <policy/mock_device_policy.h>
David Zeuthen27a48bc2013-08-06 12:06:29 -070021
22#include "update_engine/p2p_manager.h"
23#include "update_engine/fake_p2p_manager_configuration.h"
24#include "update_engine/prefs.h"
25#include "update_engine/test_utils.h"
26#include "update_engine/utils.h"
27
28using std::string;
29using std::vector;
30using base::TimeDelta;
31
32namespace chromeos_update_engine {
33
34// Test fixture that sets up a testing configuration (with e.g. a
35// temporary p2p dir) for P2PManager and cleans up when the test is
36// done.
37class P2PManagerTest : public testing::Test {
38protected:
39 P2PManagerTest() {}
40 virtual ~P2PManagerTest() {}
41
42 // Derived from testing::Test.
43 virtual void SetUp() {
44 test_conf_ = new FakeP2PManagerConfiguration();
45 }
46 virtual void TearDown() {}
47
48 // The P2PManager::Configuration instance used for testing.
49 FakeP2PManagerConfiguration *test_conf_;
50};
51
52
David Zeuthen92d9c8b2013-09-11 10:58:11 -070053// Check that IsP2PEnabled() returns false if neither the crosh flag
54// nor the Enterprise Policy indicates p2p is to be used.
55TEST_F(P2PManagerTest, P2PEnabledNeitherCroshFlagNotEnterpriseSetting) {
David Zeuthen27a48bc2013-08-06 12:06:29 -070056 string temp_dir;
57 Prefs prefs;
58 EXPECT_TRUE(utils::MakeTempDirectory("/tmp/PayloadStateP2PTests.XXXXXX",
59 &temp_dir));
60 prefs.Init(FilePath(temp_dir));
61
62 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
63 &prefs, "cros_au", 3));
64 EXPECT_FALSE(manager->IsP2PEnabled());
David Zeuthen92d9c8b2013-09-11 10:58:11 -070065
66 EXPECT_TRUE(utils::RecursiveUnlinkDir(temp_dir));
67}
68
69// Check that IsP2PEnabled() corresponds to value of the crosh flag
70// when Enterprise Policy is not set.
71TEST_F(P2PManagerTest, P2PEnabledCroshFlag) {
72 string temp_dir;
73 Prefs prefs;
74 EXPECT_TRUE(utils::MakeTempDirectory("/tmp/PayloadStateP2PTests.XXXXXX",
75 &temp_dir));
76 prefs.Init(FilePath(temp_dir));
77
78 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
79 &prefs, "cros_au", 3));
80 EXPECT_FALSE(manager->IsP2PEnabled());
81 prefs.SetBoolean(kPrefsP2PEnabled, true);
82 EXPECT_TRUE(manager->IsP2PEnabled());
83 prefs.SetBoolean(kPrefsP2PEnabled, false);
84 EXPECT_FALSE(manager->IsP2PEnabled());
85
86 EXPECT_TRUE(utils::RecursiveUnlinkDir(temp_dir));
87}
88
89// Check that IsP2PEnabled() always returns true if Enterprise Policy
90// indicates that p2p is to be used.
91TEST_F(P2PManagerTest, P2PEnabledEnterpriseSettingTrue) {
92 string temp_dir;
93 Prefs prefs;
94 EXPECT_TRUE(utils::MakeTempDirectory("/tmp/PayloadStateP2PTests.XXXXXX",
95 &temp_dir));
96 prefs.Init(FilePath(temp_dir));
97
98 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
99 &prefs, "cros_au", 3));
100 scoped_ptr<policy::MockDevicePolicy> device_policy(
101 new policy::MockDevicePolicy());
102 EXPECT_CALL(*device_policy, GetAuP2PEnabled(testing::_)).WillRepeatedly(
103 DoAll(testing::SetArgumentPointee<0>(bool(true)),
104 testing::Return(true)));
105 manager->SetDevicePolicy(device_policy.get());
106 EXPECT_TRUE(manager->IsP2PEnabled());
107
108 // Should still return true even if crosh flag says otherwise.
109 prefs.SetBoolean(kPrefsP2PEnabled, false);
110 EXPECT_TRUE(manager->IsP2PEnabled());
111
112 EXPECT_TRUE(utils::RecursiveUnlinkDir(temp_dir));
113}
114
115// Check that IsP2PEnabled() corrresponds to the value of the crosh
116// flag if Enterprise Policy indicates that p2p is not to be used.
117TEST_F(P2PManagerTest, P2PEnabledEnterpriseSettingFalse) {
118 string temp_dir;
119 Prefs prefs;
120 EXPECT_TRUE(utils::MakeTempDirectory("/tmp/PayloadStateP2PTests.XXXXXX",
121 &temp_dir));
122 prefs.Init(FilePath(temp_dir));
123
124 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
125 &prefs, "cros_au", 3));
126 scoped_ptr<policy::MockDevicePolicy> device_policy(
127 new policy::MockDevicePolicy());
128 EXPECT_CALL(*device_policy, GetAuP2PEnabled(testing::_)).WillRepeatedly(
129 DoAll(testing::SetArgumentPointee<0>(bool(false)),
130 testing::Return(true)));
131 manager->SetDevicePolicy(device_policy.get());
132 EXPECT_FALSE(manager->IsP2PEnabled());
133
David Zeuthen27a48bc2013-08-06 12:06:29 -0700134 prefs.SetBoolean(kPrefsP2PEnabled, true);
135 EXPECT_TRUE(manager->IsP2PEnabled());
136 prefs.SetBoolean(kPrefsP2PEnabled, false);
137 EXPECT_FALSE(manager->IsP2PEnabled());
138
139 EXPECT_TRUE(utils::RecursiveUnlinkDir(temp_dir));
140}
141
142// Check that we keep the $N newest files with the .$EXT.p2p extension.
David Zeuthen45e2ae22013-09-03 11:46:11 -0700143TEST_F(P2PManagerTest, Housekeeping) {
David Zeuthen27a48bc2013-08-06 12:06:29 -0700144 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
145 NULL, "cros_au", 3));
146 EXPECT_EQ(manager->CountSharedFiles(), 0);
147
Alex Deymo0f513512013-09-13 14:11:26 -0700148 // Generate files with different timestamps matching our pattern and generate
149 // other files not matching the pattern.
150 double last_timestamp = -1;
David Zeuthen27a48bc2013-08-06 12:06:29 -0700151 for (int n = 0; n < 5; n++) {
Alex Deymo0f513512013-09-13 14:11:26 -0700152 double current_timestamp;
153 do {
154 FilePath file = test_conf_->GetP2PDir().Append(StringPrintf(
155 "file_%d.cros_au.p2p", n));
156 EXPECT_EQ(0, System(StringPrintf("touch %s", file.value().c_str())));
David Zeuthen45e2ae22013-09-03 11:46:11 -0700157
Alex Deymo0f513512013-09-13 14:11:26 -0700158 // Check that the current timestamp on the file is different from the
159 // previous generated file. This timestamp depends on the file system
160 // time resolution, for example, ext2/ext3 have a time resolution of one
161 // second while ext4 has a resolution of one nanosecond. If the assigned
162 // timestamp is the same, we introduce a bigger sleep and call touch
163 // again.
164 struct stat statbuf;
165 EXPECT_EQ(stat(file.value().c_str(), &statbuf), 0);
166 current_timestamp = utils::TimeFromStructTimespec(&statbuf.st_ctim)
167 .ToDoubleT();
168 if (current_timestamp == last_timestamp)
169 sleep(1);
170 } while (current_timestamp == last_timestamp);
171 last_timestamp = current_timestamp;
172
173 EXPECT_EQ(0, System(StringPrintf("touch %s/file_%d.OTHER.p2p",
David Zeuthen27a48bc2013-08-06 12:06:29 -0700174 test_conf_->GetP2PDir().value().c_str(),
175 n)));
176
Alex Deymo0f513512013-09-13 14:11:26 -0700177 // A sleep of one micro-second is enough to have a different "Change" time
178 // on the file on newer file systems.
179 g_usleep(1);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700180 }
181 // CountSharedFiles() only counts 'cros_au' files.
182 EXPECT_EQ(manager->CountSharedFiles(), 5);
183
184 EXPECT_TRUE(manager->PerformHousekeeping());
185
186 // At this point - after HouseKeeping - we should only have
187 // eight files left.
188 for (int n = 0; n < 5; n++) {
189 string file_name;
190 bool expect;
191
192 expect = (n >= 2);
193 file_name = StringPrintf("%s/file_%d.cros_au.p2p",
194 test_conf_->GetP2PDir().value().c_str(), n);
195 EXPECT_EQ(!!g_file_test(file_name.c_str(), G_FILE_TEST_EXISTS), expect);
196
197 file_name = StringPrintf("%s/file_%d.OTHER.p2p",
198 test_conf_->GetP2PDir().value().c_str(), n);
199 EXPECT_TRUE(g_file_test(file_name.c_str(), G_FILE_TEST_EXISTS));
200 }
201 // CountSharedFiles() only counts 'cros_au' files.
202 EXPECT_EQ(manager->CountSharedFiles(), 3);
203}
204
205static bool CheckP2PFile(const string& p2p_dir, const string& file_name,
206 ssize_t expected_size, ssize_t expected_size_xattr) {
207 string path = p2p_dir + "/" + file_name;
208 struct stat statbuf;
209 char ea_value[64] = { 0 };
210 ssize_t ea_size;
211
212 if (stat(path.c_str(), &statbuf) != 0) {
213 LOG(ERROR) << "File " << path << " does not exist";
214 return false;
215 }
216
217 if (expected_size != 0) {
218 if (statbuf.st_size != expected_size) {
219 LOG(ERROR) << "Expected size " << expected_size
220 << " but size was " << statbuf.st_size;
221 return false;
222 }
223 }
224
225 if (expected_size_xattr == 0) {
226 ea_size = getxattr(path.c_str(), "user.cros-p2p-filesize",
227 &ea_value, sizeof ea_value - 1);
228 if (ea_size == -1 && errno == ENOATTR) {
229 // This is valid behavior as we support files without the xattr set.
230 } else {
231 PLOG(ERROR) << "getxattr() didn't fail with ENOATTR as expected, "
232 << "ea_size=" << ea_size << ", errno=" << errno;
233 return false;
234 }
235 } else {
236 ea_size = getxattr(path.c_str(), "user.cros-p2p-filesize",
237 &ea_value, sizeof ea_value - 1);
238 if (ea_size < 0) {
239 LOG(ERROR) << "Error getting xattr attribute";
240 return false;
241 }
242 char* endp = NULL;
243 long long int val = strtoll(ea_value, &endp, 0);
244 if (endp == NULL || *endp != '\0') {
245 LOG(ERROR) << "Error parsing xattr '" << ea_value
246 << "' as an integer";
247 return false;
248 }
249 if (val != expected_size_xattr) {
250 LOG(ERROR) << "Expected xattr size " << expected_size_xattr
251 << " but size was " << val;
252 return false;
253 }
254 }
255
256 return true;
257}
258
259static bool CreateP2PFile(string p2p_dir, string file_name,
260 size_t size, size_t size_xattr) {
261 string path = p2p_dir + "/" + file_name;
262
263 int fd = open(path.c_str(), O_CREAT|O_RDWR, 0644);
264 if (fd == -1) {
265 PLOG(ERROR) << "Error creating file with path " << path;
266 return false;
267 }
268 if (ftruncate(fd, size) != 0) {
269 PLOG(ERROR) << "Error truncating " << path << " to size " << size;
270 close(fd);
271 return false;
272 }
273
274 if (size_xattr != 0) {
275 string decimal_size = StringPrintf("%zu", size_xattr);
276 if (fsetxattr(fd, "user.cros-p2p-filesize",
277 decimal_size.c_str(), decimal_size.size(), 0) != 0) {
278 PLOG(ERROR) << "Error setting xattr on " << path;
279 close(fd);
280 return false;
281 }
282 }
283
284 close(fd);
285 return true;
286}
287
288// Check that sharing a *new* file works.
289TEST_F(P2PManagerTest, ShareFile) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700290 if (!utils::IsXAttrSupported(FilePath("/tmp"))) {
291 LOG(WARNING) << "Skipping test because /tmp does not support xattr. "
292 << "Please update your system to support this feature.";
293 return;
294 }
295
David Zeuthen27a48bc2013-08-06 12:06:29 -0700296 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
297 NULL, "cros_au", 3));
298 EXPECT_TRUE(manager->FileShare("foo", 10 * 1000 * 1000));
299 EXPECT_EQ(manager->FileGetPath("foo"),
300 test_conf_->GetP2PDir().Append("foo.cros_au.p2p.tmp"));
301 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
302 "foo.cros_au.p2p.tmp", 0, 10 * 1000 * 1000));
303
304 // Sharing it again - with the same expected size - should return true
305 EXPECT_TRUE(manager->FileShare("foo", 10 * 1000 * 1000));
306
307 // ... but if we use the wrong size, it should fail
308 EXPECT_FALSE(manager->FileShare("foo", 10 * 1000 * 1000 + 1));
309}
310
311// Check that making a shared file visible, does what is expected.
312TEST_F(P2PManagerTest, MakeFileVisible) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700313 if (!utils::IsXAttrSupported(FilePath("/tmp"))) {
314 LOG(WARNING) << "Skipping test because /tmp does not support xattr. "
315 << "Please update your system to support this feature.";
316 return;
317 }
318
David Zeuthen27a48bc2013-08-06 12:06:29 -0700319 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
320 NULL, "cros_au", 3));
321 // First, check that it's not visible.
322 manager->FileShare("foo", 10*1000*1000);
323 EXPECT_EQ(manager->FileGetPath("foo"),
324 test_conf_->GetP2PDir().Append("foo.cros_au.p2p.tmp"));
325 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
326 "foo.cros_au.p2p.tmp", 0, 10 * 1000 * 1000));
327 // Make the file visible and check that it changed its name. Do it
328 // twice to check that FileMakeVisible() is idempotent.
329 for (int n = 0; n < 2; n++) {
330 manager->FileMakeVisible("foo");
331 EXPECT_EQ(manager->FileGetPath("foo"),
332 test_conf_->GetP2PDir().Append("foo.cros_au.p2p"));
333 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
334 "foo.cros_au.p2p", 0, 10 * 1000 * 1000));
335 }
336}
337
338// Check that we return the right values for existing files in P2P_DIR.
339TEST_F(P2PManagerTest, ExistingFiles) {
David Zeuthen910ec5b2013-09-26 12:10:58 -0700340 if (!utils::IsXAttrSupported(FilePath("/tmp"))) {
341 LOG(WARNING) << "Skipping test because /tmp does not support xattr. "
342 << "Please update your system to support this feature.";
343 return;
344 }
345
David Zeuthen27a48bc2013-08-06 12:06:29 -0700346 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
347 NULL, "cros_au", 3));
348 bool visible;
349
350 // Check that errors are returned if the file does not exist
351 EXPECT_EQ(manager->FileGetPath("foo"), FilePath());
352 EXPECT_EQ(manager->FileGetSize("foo"), -1);
353 EXPECT_EQ(manager->FileGetExpectedSize("foo"), -1);
354 EXPECT_FALSE(manager->FileGetVisible("foo", NULL));
355 // ... then create the file ...
356 EXPECT_TRUE(CreateP2PFile(test_conf_->GetP2PDir().value(),
357 "foo.cros_au.p2p", 42, 43));
358 // ... and then check that the expected values are returned
359 EXPECT_EQ(manager->FileGetPath("foo"),
360 test_conf_->GetP2PDir().Append("foo.cros_au.p2p"));
361 EXPECT_EQ(manager->FileGetSize("foo"), 42);
362 EXPECT_EQ(manager->FileGetExpectedSize("foo"), 43);
363 EXPECT_TRUE(manager->FileGetVisible("foo", &visible));
364 EXPECT_TRUE(visible);
365
366 // One more time, this time with a .tmp variant. First ensure it errors out..
367 EXPECT_EQ(manager->FileGetPath("bar"), FilePath());
368 EXPECT_EQ(manager->FileGetSize("bar"), -1);
369 EXPECT_EQ(manager->FileGetExpectedSize("bar"), -1);
370 EXPECT_FALSE(manager->FileGetVisible("bar", NULL));
371 // ... then create the file ...
372 EXPECT_TRUE(CreateP2PFile(test_conf_->GetP2PDir().value(),
373 "bar.cros_au.p2p.tmp", 44, 45));
374 // ... and then check that the expected values are returned
375 EXPECT_EQ(manager->FileGetPath("bar"),
376 test_conf_->GetP2PDir().Append("bar.cros_au.p2p.tmp"));
377 EXPECT_EQ(manager->FileGetSize("bar"), 44);
378 EXPECT_EQ(manager->FileGetExpectedSize("bar"), 45);
379 EXPECT_TRUE(manager->FileGetVisible("bar", &visible));
380 EXPECT_FALSE(visible);
381}
382
David Zeuthen27a48bc2013-08-06 12:06:29 -0700383// This is a little bit ugly but short of mocking a 'p2p' service this
384// will have to do. E.g. we essentially simulate the various
385// behaviours of initctl(8) that we rely on.
386TEST_F(P2PManagerTest, StartP2P) {
387 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
388 NULL, "cros_au", 3));
389
390 // Check that we can start the service
391 test_conf_->SetInitctlStartCommandLine("true");
392 EXPECT_TRUE(manager->EnsureP2PRunning());
393 test_conf_->SetInitctlStartCommandLine("false");
394 EXPECT_FALSE(manager->EnsureP2PRunning());
395 test_conf_->SetInitctlStartCommandLine(
396 "sh -c 'echo \"initctl: Job is already running: p2p\" >&2; false'");
397 EXPECT_TRUE(manager->EnsureP2PRunning());
398 test_conf_->SetInitctlStartCommandLine(
399 "sh -c 'echo something else >&2; false'");
400 EXPECT_FALSE(manager->EnsureP2PRunning());
401}
402
403// Same comment as for StartP2P
404TEST_F(P2PManagerTest, StopP2P) {
405 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
406 NULL, "cros_au", 3));
407
408 // Check that we can start the service
409 test_conf_->SetInitctlStopCommandLine("true");
410 EXPECT_TRUE(manager->EnsureP2PNotRunning());
411 test_conf_->SetInitctlStopCommandLine("false");
412 EXPECT_FALSE(manager->EnsureP2PNotRunning());
413 test_conf_->SetInitctlStopCommandLine(
414 "sh -c 'echo \"initctl: Unknown instance \" >&2; false'");
415 EXPECT_TRUE(manager->EnsureP2PNotRunning());
416 test_conf_->SetInitctlStopCommandLine(
417 "sh -c 'echo something else >&2; false'");
418 EXPECT_FALSE(manager->EnsureP2PNotRunning());
419}
420
421static void ExpectUrl(const string& expected_url,
422 GMainLoop* loop,
423 const string& url) {
424 EXPECT_EQ(url, expected_url);
425 g_main_loop_quit(loop);
426}
427
428// Like StartP2P, we're mocking the different results that p2p-client
429// can return. It's not pretty but it works.
430TEST_F(P2PManagerTest, LookupURL) {
431 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
432 NULL, "cros_au", 3));
433 GMainLoop *loop = g_main_loop_new(NULL, FALSE);
434
435 // Emulate p2p-client returning valid URL with "fooX", 42 and "cros_au"
436 // being propagated in the right places.
437 test_conf_->SetP2PClientCommandLine("echo 'http://1.2.3.4/%s_%zu'");
438 manager->LookupUrlForFile("fooX", 42, TimeDelta(),
439 base::Bind(ExpectUrl,
440 "http://1.2.3.4/fooX.cros_au_42", loop));
441 g_main_loop_run(loop);
442
443 // Emulate p2p-client returning invalid URL.
444 test_conf_->SetP2PClientCommandLine("echo 'not_a_valid_url'");
445 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
446 base::Bind(ExpectUrl, "", loop));
447 g_main_loop_run(loop);
448
449 // Emulate p2p-client conveying failure.
450 test_conf_->SetP2PClientCommandLine("false");
451 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
452 base::Bind(ExpectUrl, "", loop));
453 g_main_loop_run(loop);
454
455 // Emulate p2p-client not existing.
456 test_conf_->SetP2PClientCommandLine("/path/to/non/existent/helper/program");
457 manager->LookupUrlForFile("foobar", 42,
458 TimeDelta(),
459 base::Bind(ExpectUrl, "", loop));
460 g_main_loop_run(loop);
461
462 // Emulate p2p-client crashing.
463 test_conf_->SetP2PClientCommandLine("sh -c 'kill -SEGV $$'");
464 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
465 base::Bind(ExpectUrl, "", loop));
466 g_main_loop_run(loop);
467
468 // Emulate p2p-client exceeding its timeout.
469 test_conf_->SetP2PClientCommandLine("sh -c 'echo http://1.2.3.4/; sleep 2'");
470 manager->LookupUrlForFile("foobar", 42, TimeDelta::FromMilliseconds(500),
471 base::Bind(ExpectUrl, "", loop));
472 g_main_loop_run(loop);
473
474 g_main_loop_unref(loop);
475}
476
477} // namespace chromeos_update_engine