blob: ce8d644a46661f3605756d0bd9ceb7f61b6bee83 [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) {
290 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
291 NULL, "cros_au", 3));
292 EXPECT_TRUE(manager->FileShare("foo", 10 * 1000 * 1000));
293 EXPECT_EQ(manager->FileGetPath("foo"),
294 test_conf_->GetP2PDir().Append("foo.cros_au.p2p.tmp"));
295 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
296 "foo.cros_au.p2p.tmp", 0, 10 * 1000 * 1000));
297
298 // Sharing it again - with the same expected size - should return true
299 EXPECT_TRUE(manager->FileShare("foo", 10 * 1000 * 1000));
300
301 // ... but if we use the wrong size, it should fail
302 EXPECT_FALSE(manager->FileShare("foo", 10 * 1000 * 1000 + 1));
303}
304
305// Check that making a shared file visible, does what is expected.
306TEST_F(P2PManagerTest, MakeFileVisible) {
307 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
308 NULL, "cros_au", 3));
309 // First, check that it's not visible.
310 manager->FileShare("foo", 10*1000*1000);
311 EXPECT_EQ(manager->FileGetPath("foo"),
312 test_conf_->GetP2PDir().Append("foo.cros_au.p2p.tmp"));
313 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
314 "foo.cros_au.p2p.tmp", 0, 10 * 1000 * 1000));
315 // Make the file visible and check that it changed its name. Do it
316 // twice to check that FileMakeVisible() is idempotent.
317 for (int n = 0; n < 2; n++) {
318 manager->FileMakeVisible("foo");
319 EXPECT_EQ(manager->FileGetPath("foo"),
320 test_conf_->GetP2PDir().Append("foo.cros_au.p2p"));
321 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
322 "foo.cros_au.p2p", 0, 10 * 1000 * 1000));
323 }
324}
325
326// Check that we return the right values for existing files in P2P_DIR.
327TEST_F(P2PManagerTest, ExistingFiles) {
328 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
329 NULL, "cros_au", 3));
330 bool visible;
331
332 // Check that errors are returned if the file does not exist
333 EXPECT_EQ(manager->FileGetPath("foo"), FilePath());
334 EXPECT_EQ(manager->FileGetSize("foo"), -1);
335 EXPECT_EQ(manager->FileGetExpectedSize("foo"), -1);
336 EXPECT_FALSE(manager->FileGetVisible("foo", NULL));
337 // ... then create the file ...
338 EXPECT_TRUE(CreateP2PFile(test_conf_->GetP2PDir().value(),
339 "foo.cros_au.p2p", 42, 43));
340 // ... and then check that the expected values are returned
341 EXPECT_EQ(manager->FileGetPath("foo"),
342 test_conf_->GetP2PDir().Append("foo.cros_au.p2p"));
343 EXPECT_EQ(manager->FileGetSize("foo"), 42);
344 EXPECT_EQ(manager->FileGetExpectedSize("foo"), 43);
345 EXPECT_TRUE(manager->FileGetVisible("foo", &visible));
346 EXPECT_TRUE(visible);
347
348 // One more time, this time with a .tmp variant. First ensure it errors out..
349 EXPECT_EQ(manager->FileGetPath("bar"), FilePath());
350 EXPECT_EQ(manager->FileGetSize("bar"), -1);
351 EXPECT_EQ(manager->FileGetExpectedSize("bar"), -1);
352 EXPECT_FALSE(manager->FileGetVisible("bar", NULL));
353 // ... then create the file ...
354 EXPECT_TRUE(CreateP2PFile(test_conf_->GetP2PDir().value(),
355 "bar.cros_au.p2p.tmp", 44, 45));
356 // ... and then check that the expected values are returned
357 EXPECT_EQ(manager->FileGetPath("bar"),
358 test_conf_->GetP2PDir().Append("bar.cros_au.p2p.tmp"));
359 EXPECT_EQ(manager->FileGetSize("bar"), 44);
360 EXPECT_EQ(manager->FileGetExpectedSize("bar"), 45);
361 EXPECT_TRUE(manager->FileGetVisible("bar", &visible));
362 EXPECT_FALSE(visible);
363}
364
David Zeuthen27a48bc2013-08-06 12:06:29 -0700365// This is a little bit ugly but short of mocking a 'p2p' service this
366// will have to do. E.g. we essentially simulate the various
367// behaviours of initctl(8) that we rely on.
368TEST_F(P2PManagerTest, StartP2P) {
369 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
370 NULL, "cros_au", 3));
371
372 // Check that we can start the service
373 test_conf_->SetInitctlStartCommandLine("true");
374 EXPECT_TRUE(manager->EnsureP2PRunning());
375 test_conf_->SetInitctlStartCommandLine("false");
376 EXPECT_FALSE(manager->EnsureP2PRunning());
377 test_conf_->SetInitctlStartCommandLine(
378 "sh -c 'echo \"initctl: Job is already running: p2p\" >&2; false'");
379 EXPECT_TRUE(manager->EnsureP2PRunning());
380 test_conf_->SetInitctlStartCommandLine(
381 "sh -c 'echo something else >&2; false'");
382 EXPECT_FALSE(manager->EnsureP2PRunning());
383}
384
385// Same comment as for StartP2P
386TEST_F(P2PManagerTest, StopP2P) {
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_->SetInitctlStopCommandLine("true");
392 EXPECT_TRUE(manager->EnsureP2PNotRunning());
393 test_conf_->SetInitctlStopCommandLine("false");
394 EXPECT_FALSE(manager->EnsureP2PNotRunning());
395 test_conf_->SetInitctlStopCommandLine(
396 "sh -c 'echo \"initctl: Unknown instance \" >&2; false'");
397 EXPECT_TRUE(manager->EnsureP2PNotRunning());
398 test_conf_->SetInitctlStopCommandLine(
399 "sh -c 'echo something else >&2; false'");
400 EXPECT_FALSE(manager->EnsureP2PNotRunning());
401}
402
403static void ExpectUrl(const string& expected_url,
404 GMainLoop* loop,
405 const string& url) {
406 EXPECT_EQ(url, expected_url);
407 g_main_loop_quit(loop);
408}
409
410// Like StartP2P, we're mocking the different results that p2p-client
411// can return. It's not pretty but it works.
412TEST_F(P2PManagerTest, LookupURL) {
413 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
414 NULL, "cros_au", 3));
415 GMainLoop *loop = g_main_loop_new(NULL, FALSE);
416
417 // Emulate p2p-client returning valid URL with "fooX", 42 and "cros_au"
418 // being propagated in the right places.
419 test_conf_->SetP2PClientCommandLine("echo 'http://1.2.3.4/%s_%zu'");
420 manager->LookupUrlForFile("fooX", 42, TimeDelta(),
421 base::Bind(ExpectUrl,
422 "http://1.2.3.4/fooX.cros_au_42", loop));
423 g_main_loop_run(loop);
424
425 // Emulate p2p-client returning invalid URL.
426 test_conf_->SetP2PClientCommandLine("echo 'not_a_valid_url'");
427 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
428 base::Bind(ExpectUrl, "", loop));
429 g_main_loop_run(loop);
430
431 // Emulate p2p-client conveying failure.
432 test_conf_->SetP2PClientCommandLine("false");
433 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
434 base::Bind(ExpectUrl, "", loop));
435 g_main_loop_run(loop);
436
437 // Emulate p2p-client not existing.
438 test_conf_->SetP2PClientCommandLine("/path/to/non/existent/helper/program");
439 manager->LookupUrlForFile("foobar", 42,
440 TimeDelta(),
441 base::Bind(ExpectUrl, "", loop));
442 g_main_loop_run(loop);
443
444 // Emulate p2p-client crashing.
445 test_conf_->SetP2PClientCommandLine("sh -c 'kill -SEGV $$'");
446 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
447 base::Bind(ExpectUrl, "", loop));
448 g_main_loop_run(loop);
449
450 // Emulate p2p-client exceeding its timeout.
451 test_conf_->SetP2PClientCommandLine("sh -c 'echo http://1.2.3.4/; sleep 2'");
452 manager->LookupUrlForFile("foobar", 42, TimeDelta::FromMilliseconds(500),
453 base::Bind(ExpectUrl, "", loop));
454 g_main_loop_run(loop);
455
456 g_main_loop_unref(loop);
457}
458
459} // namespace chromeos_update_engine