blob: 449387b3dad24a4d535a400a230fb0a8a64173b3 [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
David Zeuthend5b3e422013-08-29 13:24:26 -070071// TODO(zeuthen): This test is flaky on some builders. See http://crbug/281694
72#if 0
73
David Zeuthen27a48bc2013-08-06 12:06:29 -070074// Check that we keep the $N newest files with the .$EXT.p2p extension.
75TEST_F(P2PManagerTest, HouseKeeping) {
76 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
77 NULL, "cros_au", 3));
78 EXPECT_EQ(manager->CountSharedFiles(), 0);
79
80 // Generate files both matching our pattern and not matching them.
81 for (int n = 0; n < 5; n++) {
82 EXPECT_EQ(0, System(StringPrintf("touch %s/file_%d.cros_au.p2p",
83 test_conf_->GetP2PDir().value().c_str(),
84 n)));
85
86 EXPECT_EQ(0, System(StringPrintf("touch %s/file_%d.OTHER.p2p",
87 test_conf_->GetP2PDir().value().c_str(),
88 n)));
89
90 // Sleep one micro-second to ensure that the files all have
91 // different timestamps (time resolution for ext4 is one
92 // nano-second so sleeping a single usec is more than enough).
93 g_usleep(1);
94 }
95 // CountSharedFiles() only counts 'cros_au' files.
96 EXPECT_EQ(manager->CountSharedFiles(), 5);
97
98 EXPECT_TRUE(manager->PerformHousekeeping());
99
100 // At this point - after HouseKeeping - we should only have
101 // eight files left.
102 for (int n = 0; n < 5; n++) {
103 string file_name;
104 bool expect;
105
106 expect = (n >= 2);
107 file_name = StringPrintf("%s/file_%d.cros_au.p2p",
108 test_conf_->GetP2PDir().value().c_str(), n);
109 EXPECT_EQ(!!g_file_test(file_name.c_str(), G_FILE_TEST_EXISTS), expect);
110
111 file_name = StringPrintf("%s/file_%d.OTHER.p2p",
112 test_conf_->GetP2PDir().value().c_str(), n);
113 EXPECT_TRUE(g_file_test(file_name.c_str(), G_FILE_TEST_EXISTS));
114 }
115 // CountSharedFiles() only counts 'cros_au' files.
116 EXPECT_EQ(manager->CountSharedFiles(), 3);
117}
118
David Zeuthend5b3e422013-08-29 13:24:26 -0700119#endif // http://crbug/281694
David Zeuthenac9c1862013-08-29 10:26:13 -0700120
121// TODO(zeuthen): Some builders do not support fallocate(2) or xattrs
122// in the tmp directories where the code runs so comment out these
123// tests for now. See http://crbug.com/281496
124#if 0
125
David Zeuthen27a48bc2013-08-06 12:06:29 -0700126static bool CheckP2PFile(const string& p2p_dir, const string& file_name,
127 ssize_t expected_size, ssize_t expected_size_xattr) {
128 string path = p2p_dir + "/" + file_name;
129 struct stat statbuf;
130 char ea_value[64] = { 0 };
131 ssize_t ea_size;
132
133 if (stat(path.c_str(), &statbuf) != 0) {
134 LOG(ERROR) << "File " << path << " does not exist";
135 return false;
136 }
137
138 if (expected_size != 0) {
139 if (statbuf.st_size != expected_size) {
140 LOG(ERROR) << "Expected size " << expected_size
141 << " but size was " << statbuf.st_size;
142 return false;
143 }
144 }
145
146 if (expected_size_xattr == 0) {
147 ea_size = getxattr(path.c_str(), "user.cros-p2p-filesize",
148 &ea_value, sizeof ea_value - 1);
149 if (ea_size == -1 && errno == ENOATTR) {
150 // This is valid behavior as we support files without the xattr set.
151 } else {
152 PLOG(ERROR) << "getxattr() didn't fail with ENOATTR as expected, "
153 << "ea_size=" << ea_size << ", errno=" << errno;
154 return false;
155 }
156 } else {
157 ea_size = getxattr(path.c_str(), "user.cros-p2p-filesize",
158 &ea_value, sizeof ea_value - 1);
159 if (ea_size < 0) {
160 LOG(ERROR) << "Error getting xattr attribute";
161 return false;
162 }
163 char* endp = NULL;
164 long long int val = strtoll(ea_value, &endp, 0);
165 if (endp == NULL || *endp != '\0') {
166 LOG(ERROR) << "Error parsing xattr '" << ea_value
167 << "' as an integer";
168 return false;
169 }
170 if (val != expected_size_xattr) {
171 LOG(ERROR) << "Expected xattr size " << expected_size_xattr
172 << " but size was " << val;
173 return false;
174 }
175 }
176
177 return true;
178}
179
180static bool CreateP2PFile(string p2p_dir, string file_name,
181 size_t size, size_t size_xattr) {
182 string path = p2p_dir + "/" + file_name;
183
184 int fd = open(path.c_str(), O_CREAT|O_RDWR, 0644);
185 if (fd == -1) {
186 PLOG(ERROR) << "Error creating file with path " << path;
187 return false;
188 }
189 if (ftruncate(fd, size) != 0) {
190 PLOG(ERROR) << "Error truncating " << path << " to size " << size;
191 close(fd);
192 return false;
193 }
194
195 if (size_xattr != 0) {
196 string decimal_size = StringPrintf("%zu", size_xattr);
197 if (fsetxattr(fd, "user.cros-p2p-filesize",
198 decimal_size.c_str(), decimal_size.size(), 0) != 0) {
199 PLOG(ERROR) << "Error setting xattr on " << path;
200 close(fd);
201 return false;
202 }
203 }
204
205 close(fd);
206 return true;
207}
208
209// Check that sharing a *new* file works.
210TEST_F(P2PManagerTest, ShareFile) {
211 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
212 NULL, "cros_au", 3));
213 EXPECT_TRUE(manager->FileShare("foo", 10 * 1000 * 1000));
214 EXPECT_EQ(manager->FileGetPath("foo"),
215 test_conf_->GetP2PDir().Append("foo.cros_au.p2p.tmp"));
216 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
217 "foo.cros_au.p2p.tmp", 0, 10 * 1000 * 1000));
218
219 // Sharing it again - with the same expected size - should return true
220 EXPECT_TRUE(manager->FileShare("foo", 10 * 1000 * 1000));
221
222 // ... but if we use the wrong size, it should fail
223 EXPECT_FALSE(manager->FileShare("foo", 10 * 1000 * 1000 + 1));
224}
225
226// Check that making a shared file visible, does what is expected.
227TEST_F(P2PManagerTest, MakeFileVisible) {
228 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
229 NULL, "cros_au", 3));
230 // First, check that it's not visible.
231 manager->FileShare("foo", 10*1000*1000);
232 EXPECT_EQ(manager->FileGetPath("foo"),
233 test_conf_->GetP2PDir().Append("foo.cros_au.p2p.tmp"));
234 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
235 "foo.cros_au.p2p.tmp", 0, 10 * 1000 * 1000));
236 // Make the file visible and check that it changed its name. Do it
237 // twice to check that FileMakeVisible() is idempotent.
238 for (int n = 0; n < 2; n++) {
239 manager->FileMakeVisible("foo");
240 EXPECT_EQ(manager->FileGetPath("foo"),
241 test_conf_->GetP2PDir().Append("foo.cros_au.p2p"));
242 EXPECT_TRUE(CheckP2PFile(test_conf_->GetP2PDir().value(),
243 "foo.cros_au.p2p", 0, 10 * 1000 * 1000));
244 }
245}
246
247// Check that we return the right values for existing files in P2P_DIR.
248TEST_F(P2PManagerTest, ExistingFiles) {
249 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
250 NULL, "cros_au", 3));
251 bool visible;
252
253 // Check that errors are returned if the file does not exist
254 EXPECT_EQ(manager->FileGetPath("foo"), FilePath());
255 EXPECT_EQ(manager->FileGetSize("foo"), -1);
256 EXPECT_EQ(manager->FileGetExpectedSize("foo"), -1);
257 EXPECT_FALSE(manager->FileGetVisible("foo", NULL));
258 // ... then create the file ...
259 EXPECT_TRUE(CreateP2PFile(test_conf_->GetP2PDir().value(),
260 "foo.cros_au.p2p", 42, 43));
261 // ... and then check that the expected values are returned
262 EXPECT_EQ(manager->FileGetPath("foo"),
263 test_conf_->GetP2PDir().Append("foo.cros_au.p2p"));
264 EXPECT_EQ(manager->FileGetSize("foo"), 42);
265 EXPECT_EQ(manager->FileGetExpectedSize("foo"), 43);
266 EXPECT_TRUE(manager->FileGetVisible("foo", &visible));
267 EXPECT_TRUE(visible);
268
269 // One more time, this time with a .tmp variant. First ensure it errors out..
270 EXPECT_EQ(manager->FileGetPath("bar"), FilePath());
271 EXPECT_EQ(manager->FileGetSize("bar"), -1);
272 EXPECT_EQ(manager->FileGetExpectedSize("bar"), -1);
273 EXPECT_FALSE(manager->FileGetVisible("bar", NULL));
274 // ... then create the file ...
275 EXPECT_TRUE(CreateP2PFile(test_conf_->GetP2PDir().value(),
276 "bar.cros_au.p2p.tmp", 44, 45));
277 // ... and then check that the expected values are returned
278 EXPECT_EQ(manager->FileGetPath("bar"),
279 test_conf_->GetP2PDir().Append("bar.cros_au.p2p.tmp"));
280 EXPECT_EQ(manager->FileGetSize("bar"), 44);
281 EXPECT_EQ(manager->FileGetExpectedSize("bar"), 45);
282 EXPECT_TRUE(manager->FileGetVisible("bar", &visible));
283 EXPECT_FALSE(visible);
284}
285
David Zeuthenac9c1862013-08-29 10:26:13 -0700286#endif // http://crbug.com/281496
287
David Zeuthen27a48bc2013-08-06 12:06:29 -0700288// This is a little bit ugly but short of mocking a 'p2p' service this
289// will have to do. E.g. we essentially simulate the various
290// behaviours of initctl(8) that we rely on.
291TEST_F(P2PManagerTest, StartP2P) {
292 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
293 NULL, "cros_au", 3));
294
295 // Check that we can start the service
296 test_conf_->SetInitctlStartCommandLine("true");
297 EXPECT_TRUE(manager->EnsureP2PRunning());
298 test_conf_->SetInitctlStartCommandLine("false");
299 EXPECT_FALSE(manager->EnsureP2PRunning());
300 test_conf_->SetInitctlStartCommandLine(
301 "sh -c 'echo \"initctl: Job is already running: p2p\" >&2; false'");
302 EXPECT_TRUE(manager->EnsureP2PRunning());
303 test_conf_->SetInitctlStartCommandLine(
304 "sh -c 'echo something else >&2; false'");
305 EXPECT_FALSE(manager->EnsureP2PRunning());
306}
307
308// Same comment as for StartP2P
309TEST_F(P2PManagerTest, StopP2P) {
310 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
311 NULL, "cros_au", 3));
312
313 // Check that we can start the service
314 test_conf_->SetInitctlStopCommandLine("true");
315 EXPECT_TRUE(manager->EnsureP2PNotRunning());
316 test_conf_->SetInitctlStopCommandLine("false");
317 EXPECT_FALSE(manager->EnsureP2PNotRunning());
318 test_conf_->SetInitctlStopCommandLine(
319 "sh -c 'echo \"initctl: Unknown instance \" >&2; false'");
320 EXPECT_TRUE(manager->EnsureP2PNotRunning());
321 test_conf_->SetInitctlStopCommandLine(
322 "sh -c 'echo something else >&2; false'");
323 EXPECT_FALSE(manager->EnsureP2PNotRunning());
324}
325
326static void ExpectUrl(const string& expected_url,
327 GMainLoop* loop,
328 const string& url) {
329 EXPECT_EQ(url, expected_url);
330 g_main_loop_quit(loop);
331}
332
333// Like StartP2P, we're mocking the different results that p2p-client
334// can return. It's not pretty but it works.
335TEST_F(P2PManagerTest, LookupURL) {
336 scoped_ptr<P2PManager> manager(P2PManager::Construct(test_conf_,
337 NULL, "cros_au", 3));
338 GMainLoop *loop = g_main_loop_new(NULL, FALSE);
339
340 // Emulate p2p-client returning valid URL with "fooX", 42 and "cros_au"
341 // being propagated in the right places.
342 test_conf_->SetP2PClientCommandLine("echo 'http://1.2.3.4/%s_%zu'");
343 manager->LookupUrlForFile("fooX", 42, TimeDelta(),
344 base::Bind(ExpectUrl,
345 "http://1.2.3.4/fooX.cros_au_42", loop));
346 g_main_loop_run(loop);
347
348 // Emulate p2p-client returning invalid URL.
349 test_conf_->SetP2PClientCommandLine("echo 'not_a_valid_url'");
350 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
351 base::Bind(ExpectUrl, "", loop));
352 g_main_loop_run(loop);
353
354 // Emulate p2p-client conveying failure.
355 test_conf_->SetP2PClientCommandLine("false");
356 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
357 base::Bind(ExpectUrl, "", loop));
358 g_main_loop_run(loop);
359
360 // Emulate p2p-client not existing.
361 test_conf_->SetP2PClientCommandLine("/path/to/non/existent/helper/program");
362 manager->LookupUrlForFile("foobar", 42,
363 TimeDelta(),
364 base::Bind(ExpectUrl, "", loop));
365 g_main_loop_run(loop);
366
367 // Emulate p2p-client crashing.
368 test_conf_->SetP2PClientCommandLine("sh -c 'kill -SEGV $$'");
369 manager->LookupUrlForFile("foobar", 42, TimeDelta(),
370 base::Bind(ExpectUrl, "", loop));
371 g_main_loop_run(loop);
372
373 // Emulate p2p-client exceeding its timeout.
374 test_conf_->SetP2PClientCommandLine("sh -c 'echo http://1.2.3.4/; sleep 2'");
375 manager->LookupUrlForFile("foobar", 42, TimeDelta::FromMilliseconds(500),
376 base::Bind(ExpectUrl, "", loop));
377 g_main_loop_run(loop);
378
379 g_main_loop_unref(loop);
380}
381
382} // namespace chromeos_update_engine