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