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