Mike Frysinger | 57538c0 | 2016-10-06 23:01:33 -0400 | [diff] [blame^] | 1 | // 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 | |
| 13 | namespace debugd { |
| 14 | |
| 15 | namespace { |
| 16 | |
| 17 | // This script holds the bulk of the real logic. |
| 18 | const char kSwapHelperScript[] = "/usr/share/cros/init/swap.sh"; |
| 19 | |
| 20 | std::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 | |
| 30 | std::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 | |
| 46 | std::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 | |
| 60 | std::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 | |
| 76 | std::string SwapTool::SwapStatus(DBus::Error* error) const { |
| 77 | int result; |
| 78 | return RunSwapHelper({"status", }, &result); |
| 79 | } |
| 80 | |
| 81 | } // namespace debugd |