blob: f9d428c7144fd88e08ae0c2ad920837147f97dbb [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"
19
20#include "update_engine/p2p_manager.h"
21#include "update_engine/fake_p2p_manager_configuration.h"
22#include "update_engine/prefs.h"
23#include "update_engine/test_utils.h"
24#include "update_engine/utils.h"
25
26using std::string;
27using std::vector;
28using base::TimeDelta;
29
30namespace chromeos_update_engine {
31
32// Test fixture that sets up a testing configuration (with e.g. a
33// temporary p2p dir) for P2PManager and cleans up when the test is
34// done.
35class P2PManagerTest : public testing::Test {
36protected:
37 P2PManagerTest() {}
38 virtual ~P2PManagerTest() {}
39
40 // Derived from testing::Test.
41 virtual void SetUp() {
42 test_conf_ = new FakeP2PManagerConfiguration();
43 }
44 virtual void TearDown() {}
45
46 // The P2PManager::Configuration instance used for testing.
47 FakeP2PManagerConfiguration *test_conf_;
48};
49
50
51// Check that result of IsP2PEnabled() correspond to the
52// kPrefsP2PEnabled state variable.
53TEST_F(P2PManagerTest, P2PEnabled) {
54 string temp_dir;
55 Prefs prefs;
56 EXPECT_TRUE(utils::MakeTempDirectory("/tmp/PayloadStateP2PTests.XXXXXX",
57 &temp_dir));
58 prefs.Init(FilePath(temp_dir));
59
60 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
61 &prefs, "cros_au", 3));
62 EXPECT_FALSE(manager->IsP2PEnabled());
63 prefs.SetBoolean(kPrefsP2PEnabled, true);
64 EXPECT_TRUE(manager->IsP2PEnabled());
65 prefs.SetBoolean(kPrefsP2PEnabled, false);
66 EXPECT_FALSE(manager->IsP2PEnabled());
67
68 EXPECT_TRUE(utils::RecursiveUnlinkDir(temp_dir));
69}
70
71// Check that we keep the $N newest files with the .$EXT.p2p extension.
David Zeuthen45e2ae22013-09-03 11:46:11 -070072TEST_F(P2PManagerTest, Housekeeping) {
David Zeuthen27a48bc2013-08-06 12:06:29 -070073 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
74 NULL, "cros_au", 3));
75 EXPECT_EQ(manager->CountSharedFiles(), 0);
76
Alex Deymo0f513512013-09-13 14:11:26 -070077 // Generate files with different timestamps matching our pattern and generate
78 // other files not matching the pattern.
79 double last_timestamp = -1;
David Zeuthen27a48bc2013-08-06 12:06:29 -070080 for (int n = 0; n < 5; n++) {
Alex Deymo0f513512013-09-13 14:11:26 -070081 double current_timestamp;
82 do {
83 FilePath file = test_conf_->GetP2PDir().Append(StringPrintf(
84 "file_%d.cros_au.p2p", n));
85 EXPECT_EQ(0, System(StringPrintf("touch %s", file.value().c_str())));
David Zeuthen45e2ae22013-09-03 11:46:11 -070086
Alex Deymo0f513512013-09-13 14:11:26 -070087 // Check that the current timestamp on the file is different from the
88 // previous generated file. This timestamp depends on the file system
89 // time resolution, for example, ext2/ext3 have a time resolution of one
90 // second while ext4 has a resolution of one nanosecond. If the assigned
91 // timestamp is the same, we introduce a bigger sleep and call touch
92 // again.
93 struct stat statbuf;
94 EXPECT_EQ(stat(file.value().c_str(), &statbuf), 0);
95 current_timestamp = utils::TimeFromStructTimespec(&statbuf.st_ctim)
96 .ToDoubleT();
97 if (current_timestamp == last_timestamp)
98 sleep(1);
99 } while (current_timestamp == last_timestamp);
100 last_timestamp = current_timestamp;
101
102 EXPECT_EQ(0, System(StringPrintf("touch %s/file_%d.OTHER.p2p",
David Zeuthen27a48bc2013-08-06 12:06:29 -0700103 test_conf_->GetP2PDir().value().c_str(),
104 n)));
105
Alex Deymo0f513512013-09-13 14:11:26 -0700106 // A sleep of one micro-second is enough to have a different "Change" time
107 // on the file on newer file systems.
108 g_usleep(1);
David Zeuthen27a48bc2013-08-06 12:06:29 -0700109 }
110 // CountSharedFiles() only counts 'cros_au' files.
111 EXPECT_EQ(manager->CountSharedFiles(), 5);
112
113 EXPECT_TRUE(manager->PerformHousekeeping());
114
115 // At this point - after HouseKeeping - we should only have
116 // eight files left.
117 for (int n = 0; n < 5; n++) {
118 string file_name;
119 bool expect;
120
121 expect = (n >= 2);
122 file_name = StringPrintf("%s/file_%d.cros_au.p2p",
123 test_conf_->GetP2PDir().value().c_str(), n);
124 EXPECT_EQ(!!g_file_test(file_name.c_str(), G_FILE_TEST_EXISTS), expect);
125
126 file_name = StringPrintf("%s/file_%d.OTHER.p2p",
127 test_conf_->GetP2PDir().value().c_str(), n);
128 EXPECT_TRUE(g_file_test(file_name.c_str(), G_FILE_TEST_EXISTS));
129 }
130 // CountSharedFiles() only counts 'cros_au' files.
131 EXPECT_EQ(manager->CountSharedFiles(), 3);
132}
133
David Zeuthenac9c1862013-08-29 10:26:13 -0700134// TODO(zeuthen): Some builders do not support fallocate(2) or xattrs
135// in the tmp directories where the code runs so comment out these
136// tests for now. See http://crbug.com/281496
137#if 0
138
David Zeuthen27a48bc2013-08-06 12:06:29 -0700139static bool CheckP2PFile(const string& p2p_dir, const string& file_name,
140 ssize_t expected_size, ssize_t expected_size_xattr) {
141 string path = p2p_dir + "/" + file_name;
142 struct stat statbuf;
143 char ea_value[64] = { 0 };
144 ssize_t ea_size;
145
146 if (stat(path.c_str(), &statbuf) != 0) {
147 LOG(ERROR) << "File " << path << " does not exist";
148 return false;
149 }
150
151 if (expected_size != 0) {
152 if (statbuf.st_size != expected_size) {
153 LOG(ERROR) << "Expected size " << expected_size
154 << " but size was " << statbuf.st_size;
155 return false;
156 }
157 }
158
159 if (expected_size_xattr == 0) {
160 ea_size = getxattr(path.c_str(), "user.cros-p2p-filesize",
161 &ea_value, sizeof ea_value - 1);
162 if (ea_size == -1 && errno == ENOATTR) {
163 // This is valid behavior as we support files without the xattr set.
164 } else {
165 PLOG(ERROR) << "getxattr() didn't fail with ENOATTR as expected, "
166 << "ea_size=" << ea_size << ", errno=" << errno;
167 return false;
168 }
169 } else {
170 ea_size = getxattr(path.c_str(), "user.cros-p2p-filesize",
171 &ea_value, sizeof ea_value - 1);
172 if (ea_size < 0) {
173 LOG(ERROR) << "Error getting xattr attribute";
174 return false;
175 }
176 char* endp = NULL;
177 long long int val = strtoll(ea_value, &endp, 0);
178 if (endp == NULL || *endp != '\0') {
179 LOG(ERROR) << "Error parsing xattr '" << ea_value
180 << "' as an integer";
181 return false;
182 }
183 if (val != expected_size_xattr) {
184 LOG(ERROR) << "Expected xattr size " << expected_size_xattr
185 << " but size was " << val;
186 return false;
187 }
188 }
189
190 return true;
191}
192
193static bool CreateP2PFile(string p2p_dir, string file_name,
194 size_t size, size_t size_xattr) {
195 string path = p2p_dir + "/" + file_name;
196
197 int fd = open(path.c_str(), O_CREAT|O_RDWR, 0644);
198 if (fd == -1) {
199 PLOG(ERROR) << "Error creating file with path " << path;
200 return false;
201 }
202 if (ftruncate(fd, size) != 0) {
203 PLOG(ERROR) << "Error truncating " << path << " to size " << size;
204 close(fd);
205 return false;
206 }
207
208 if (size_xattr != 0) {
209 string decimal_size = StringPrintf("%zu", size_xattr);
210 if (fsetxattr(fd, "user.cros-p2p-filesize",
211 decimal_size.c_str(), decimal_size.size(), 0) != 0) {
212 PLOG(ERROR) << "Error setting xattr on " << path;
213 close(fd);
214 return false;
215 }
216 }
217
218 close(fd);
219 return true;
220}
221
222// Check that sharing a *new* file works.
223TEST_F(P2PManagerTest, ShareFile) {
224 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
225 NULL, "cros_au", 3));
226 EXPECT_TRUE(manager->FileShare("foo", 10 * 1000 * 1000));
227 EXPECT_EQ(manager->FileGetPath("foo"),
228 test_conf_->GetP2PDir().Append("foo.cros_au.p2p.tmp"));
229 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
230 "foo.cros_au.p2p.tmp", 0, 10 * 1000 * 1000));
231
232 // Sharing it again - with the same expected size - should return true
233 EXPECT_TRUE(manager->FileShare("foo", 10 * 1000 * 1000));
234
235 // ... but if we use the wrong size, it should fail
236 EXPECT_FALSE(manager->FileShare("foo", 10 * 1000 * 1000 + 1));
237}
238
239// Check that making a shared file visible, does what is expected.
240TEST_F(P2PManagerTest, MakeFileVisible) {
241 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
242 NULL, "cros_au", 3));
243 // First, check that it's not visible.
244 manager->FileShare("foo", 10*1000*1000);
245 EXPECT_EQ(manager->FileGetPath("foo"),
246 test_conf_->GetP2PDir().Append("foo.cros_au.p2p.tmp"));
247 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
248 "foo.cros_au.p2p.tmp", 0, 10 * 1000 * 1000));
249 // Make the file visible and check that it changed its name. Do it
250 // twice to check that FileMakeVisible() is idempotent.
251 for (int n = 0; n < 2; n++) {
252 manager->FileMakeVisible("foo");
253 EXPECT_EQ(manager->FileGetPath("foo"),
254 test_conf_->GetP2PDir().Append("foo.cros_au.p2p"));
255 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
256 "foo.cros_au.p2p", 0, 10 * 1000 * 1000));
257 }
258}
259
260// Check that we return the right values for existing files in P2P_DIR.
261TEST_F(P2PManagerTest, ExistingFiles) {
262 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
263 NULL, "cros_au", 3));
264 bool visible;
265
266 // Check that errors are returned if the file does not exist
267 EXPECT_EQ(manager->FileGetPath("foo"), FilePath());
268 EXPECT_EQ(manager->FileGetSize("foo"), -1);
269 EXPECT_EQ(manager->FileGetExpectedSize("foo"), -1);
270 EXPECT_FALSE(manager->FileGetVisible("foo", NULL));
271 // ... then create the file ...
272 EXPECT_TRUE(CreateP2PFile(test_conf_->GetP2PDir().value(),
273 "foo.cros_au.p2p", 42, 43));
274 // ... and then check that the expected values are returned
275 EXPECT_EQ(manager->FileGetPath("foo"),
276 test_conf_->GetP2PDir().Append("foo.cros_au.p2p"));
277 EXPECT_EQ(manager->FileGetSize("foo"), 42);
278 EXPECT_EQ(manager->FileGetExpectedSize("foo"), 43);
279 EXPECT_TRUE(manager->FileGetVisible("foo", &visible));
280 EXPECT_TRUE(visible);
281
282 // One more time, this time with a .tmp variant. First ensure it errors out..
283 EXPECT_EQ(manager->FileGetPath("bar"), FilePath());
284 EXPECT_EQ(manager->FileGetSize("bar"), -1);
285 EXPECT_EQ(manager->FileGetExpectedSize("bar"), -1);
286 EXPECT_FALSE(manager->FileGetVisible("bar", NULL));
287 // ... then create the file ...
288 EXPECT_TRUE(CreateP2PFile(test_conf_->GetP2PDir().value(),
289 "bar.cros_au.p2p.tmp", 44, 45));
290 // ... and then check that the expected values are returned
291 EXPECT_EQ(manager->FileGetPath("bar"),
292 test_conf_->GetP2PDir().Append("bar.cros_au.p2p.tmp"));
293 EXPECT_EQ(manager->FileGetSize("bar"), 44);
294 EXPECT_EQ(manager->FileGetExpectedSize("bar"), 45);
295 EXPECT_TRUE(manager->FileGetVisible("bar", &visible));
296 EXPECT_FALSE(visible);
297}
298
David Zeuthenac9c1862013-08-29 10:26:13 -0700299#endif // http://crbug.com/281496
300
David Zeuthen27a48bc2013-08-06 12:06:29 -0700301// This is a little bit ugly but short of mocking a 'p2p' service this
302// will have to do. E.g. we essentially simulate the various
303// behaviours of initctl(8) that we rely on.
304TEST_F(P2PManagerTest, StartP2P) {
305 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
306 NULL, "cros_au", 3));
307
308 // Check that we can start the service
309 test_conf_->SetInitctlStartCommandLine("true");
310 EXPECT_TRUE(manager->EnsureP2PRunning());
311 test_conf_->SetInitctlStartCommandLine("false");
312 EXPECT_FALSE(manager->EnsureP2PRunning());
313 test_conf_->SetInitctlStartCommandLine(
314 "sh -c 'echo \"initctl: Job is already running: p2p\" >&2; false'");
315 EXPECT_TRUE(manager->EnsureP2PRunning());
316 test_conf_->SetInitctlStartCommandLine(
317 "sh -c 'echo something else >&2; false'");
318 EXPECT_FALSE(manager->EnsureP2PRunning());
319}
320
321// Same comment as for StartP2P
322TEST_F(P2PManagerTest, StopP2P) {
323 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
324 NULL, "cros_au", 3));
325
326 // Check that we can start the service
327 test_conf_->SetInitctlStopCommandLine("true");
328 EXPECT_TRUE(manager->EnsureP2PNotRunning());
329 test_conf_->SetInitctlStopCommandLine("false");
330 EXPECT_FALSE(manager->EnsureP2PNotRunning());
331 test_conf_->SetInitctlStopCommandLine(
332 "sh -c 'echo \"initctl: Unknown instance \" >&2; false'");
333 EXPECT_TRUE(manager->EnsureP2PNotRunning());
334 test_conf_->SetInitctlStopCommandLine(
335 "sh -c 'echo something else >&2; false'");
336 EXPECT_FALSE(manager->EnsureP2PNotRunning());
337}
338
339static void ExpectUrl(const string& expected_url,
340 GMainLoop* loop,
341 const string& url) {
342 EXPECT_EQ(url, expected_url);
343 g_main_loop_quit(loop);
344}
345
346// Like StartP2P, we're mocking the different results that p2p-client
347// can return. It's not pretty but it works.
348TEST_F(P2PManagerTest, LookupURL) {
349 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
350 NULL, "cros_au", 3));
351 GMainLoop *loop = g_main_loop_new(NULL, FALSE);
352
353 // Emulate p2p-client returning valid URL with "fooX", 42 and "cros_au"
354 // being propagated in the right places.
355 test_conf_->SetP2PClientCommandLine("echo 'http://1.2.3.4/%s_%zu'");
356 manager->LookupUrlForFile("fooX", 42, TimeDelta(),
357 base::Bind(ExpectUrl,
358 "http://1.2.3.4/fooX.cros_au_42", loop));
359 g_main_loop_run(loop);
360
361 // Emulate p2p-client returning invalid URL.
362 test_conf_->SetP2PClientCommandLine("echo 'not_a_valid_url'");
363 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
364 base::Bind(ExpectUrl, "", loop));
365 g_main_loop_run(loop);
366
367 // Emulate p2p-client conveying failure.
368 test_conf_->SetP2PClientCommandLine("false");
369 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
370 base::Bind(ExpectUrl, "", loop));
371 g_main_loop_run(loop);
372
373 // Emulate p2p-client not existing.
374 test_conf_->SetP2PClientCommandLine("/path/to/non/existent/helper/program");
375 manager->LookupUrlForFile("foobar", 42,
376 TimeDelta(),
377 base::Bind(ExpectUrl, "", loop));
378 g_main_loop_run(loop);
379
380 // Emulate p2p-client crashing.
381 test_conf_->SetP2PClientCommandLine("sh -c 'kill -SEGV $$'");
382 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
383 base::Bind(ExpectUrl, "", loop));
384 g_main_loop_run(loop);
385
386 // Emulate p2p-client exceeding its timeout.
387 test_conf_->SetP2PClientCommandLine("sh -c 'echo http://1.2.3.4/; sleep 2'");
388 manager->LookupUrlForFile("foobar", 42, TimeDelta::FromMilliseconds(500),
389 base::Bind(ExpectUrl, "", loop));
390 g_main_loop_run(loop);
391
392 g_main_loop_unref(loop);
393}
394
395} // namespace chromeos_update_engine