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