blob: 64ba834b89c0f00e115ca559830e6a877d61ec0e [file] [log] [blame]
Mike Frysinger57538c02016-10-06 23:01:33 -04001// Copyright 2016 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 "debugd/src/swap_tool.h"
6
7#include <string>
8
9#include <base/strings/stringprintf.h>
10
11#include "debugd/src/process_with_output.h"
12
13namespace debugd {
14
15namespace {
16
17// This script holds the bulk of the real logic.
18const char kSwapHelperScript[] = "/usr/share/cros/init/swap.sh";
19
20std::string RunSwapHelper(const ProcessWithOutput::ArgList& arguments,
21 int* result) {
22 std::string stdout, stderr;
23 *result = ProcessWithOutput::RunProcessFromHelper(
24 kSwapHelperScript, arguments, nullptr, &stdout, &stderr);
25 return *result ? stderr : stdout;
26}
27
28} // namespace
29
30std::string SwapTool::SwapEnable(uint32_t size, bool change_now,
31 DBus::Error* error) const {
32 int result;
33 std::string output, buf;
34
35 buf = base::StringPrintf("%u", size);
36 output = RunSwapHelper({"enable", buf}, &result);
37 if (result != EXIT_SUCCESS)
38 return output;
39
40 if (change_now)
41 output = SwapStartStop(true, error);
42
43 return output;
44}
45
46std::string SwapTool::SwapDisable(bool change_now, DBus::Error* error) const {
47 int result;
48 std::string output;
49
50 output = RunSwapHelper({"disable", }, &result);
51 if (result != EXIT_SUCCESS)
52 return output;
53
54 if (change_now)
55 output = SwapStartStop(false, error);
56
57 return output;
58}
59
60std::string SwapTool::SwapStartStop(bool on, DBus::Error* error) const {
61 int result;
62 std::string output;
63
64 // We always turn off swap because the config might have changed.
65 // Also because the code doesn't like to turn on twice.
66 output = RunSwapHelper({"stop", }, &result);
67 if (result != EXIT_SUCCESS)
68 return output;
69
70 if (on)
71 output = RunSwapHelper({"start", }, &result);
72
73 return output;
74}
75
76std::string SwapTool::SwapStatus(DBus::Error* error) const {
77 int result;
78 return RunSwapHelper({"status", }, &result);
79}
80
81} // namespace debugd