나는 이것에 대해 꽤 많은 게시물을 읽었지만 여전히 다음과 같은 가정하에 올바른 접근법에 대해 확신이 없습니다. 추가 스토리지를 사용하여 새 디스크를 생성하는 대신 기존 VM 스토리지를 사용하여 스왑을 생성하려고합니다
나는 또한 이것을 필요로했다.
내가 읽은 게시물 :
그러나 내가 당신이 지적한 너무 긴 수필을 읽어야한다는 것을 알았을 때 나는 포기하려고했지만 ... 갑자기 DigitalOcean의 블로그에서 매우 간단한 기사를 기억했습니다.
우분투 14.04에서 스왑을 추가하는 방법
너무 간단하여 스크립트를 작성했습니다 (적어도 가장 좋은 부분은 아직 스왑 피스 설정 및 기타 고급 항목이 아님).
#!/usr/bin/env fsharpi
open System
open System.IO
open System.Net
open System.Diagnostics
#load "InfraTools.fs"
open Gatecoin.Infrastructure
// automation of https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04
let NUMBER_OF_GB_FOR_SWAP = 1
let isThereSwapMemoryInTheSystem (): bool =
let _,output,_ = Tools.SafeHiddenExec("swapon", "-s")
(output.Trim().Length > 0)
if (isThereSwapMemoryInTheSystem()) then
Console.WriteLine("Swap already setup")
Environment.Exit(0)
let swapFile = new FileInfo(Path.Combine("/", "swapfile"))
if not (swapFile.Exists) then
Tools.BailIfNotSudoer("Need to use 'fallocate' to create swap file")
Console.WriteLine("Creating swap file...")
Tools.SafeExec("fallocate", String.Format("-l {0}G {1}", NUMBER_OF_GB_FOR_SWAP, swapFile.FullName), true)
let permissionsForSwapFile = 600
if not (Tools.OctalPermissions(swapFile) = permissionsForSwapFile) then
Tools.BailIfNotSudoer("Need to adjust permissions of the swap file")
Tools.SafeExec("chmod", String.Format("{0} {1}", permissionsForSwapFile, swapFile.FullName), true)
Tools.BailIfNotSudoer("Enable swap memory")
Tools.SafeExec("mkswap", swapFile.FullName, true)
Tools.SafeExec("swapon", swapFile.FullName, true)
if not (isThereSwapMemoryInTheSystem()) then
Console.WriteLine("Something went wrong while enabling the swap file")
Environment.Exit(1)
Tools.BailIfNotSudoer("Writing into /etc/fstab")
Tools.SafeHiddenExecBashCommand(String.Format("echo \"{0} none swap sw 0 0\" >> /etc/fstab", swapFile.FullName))
위의 작업을 수행하려면 sudo apt install fsharp
먼저 해야합니다 (최소한 Ubuntu 16.04는 리포지토리에서 선명하지 않으며 14.04는 확실하지 않습니다).
또한이 InfraTools.fs
파일 이 필요 합니다 :
open System
open System.IO
open System.Net
namespace Gatecoin.Infrastructure
module Tools =
let HiddenExec (command: string, arguments: string) =
let startInfo = new System.Diagnostics.ProcessStartInfo(command)
startInfo.Arguments <- arguments
startInfo.UseShellExecute <- false
// equivalent to `>/dev/null 2>&1` in unix
startInfo.RedirectStandardError <- true
startInfo.RedirectStandardOutput <- true
use proc = System.Diagnostics.Process.Start(startInfo)
proc.WaitForExit()
(proc.ExitCode,proc.StandardOutput.ReadToEnd(),proc.StandardError.ReadToEnd())
let HiddenExecBashCommand (commandWithArguments: string) =
let args = String.Format("-c \"{0}\"", commandWithArguments.Replace("\"", "\\\""))
HiddenExec("bash", args)
let SafeHiddenExecBashCommand (commandWithArguments: string) =
let exitCode,stdOut,stdErr = HiddenExecBashCommand commandWithArguments
if not (exitCode = 0) then
Console.Error.WriteLine(stdErr)
Console.Error.WriteLine()
Console.Error.WriteLine("Bash command '{0}' failed with exit code {1}.", commandWithArguments, exitCode.ToString())
Environment.Exit(1)
exitCode,stdOut,stdErr
let Exec (command: string, arguments: string, echo: bool) =
let psi = new System.Diagnostics.ProcessStartInfo(command)
psi.Arguments <- arguments
psi.UseShellExecute <- false
if (echo) then
Console.WriteLine("{0} {1}", command, arguments)
let p = System.Diagnostics.Process.Start(psi)
p.WaitForExit()
p.ExitCode
let ExecBashCommand (commandWithArguments: string, echo: bool) =
let args = String.Format("-c \"{0}\"", commandWithArguments.Replace("\"", "\\\""))
if (echo) then
Console.WriteLine(commandWithArguments)
Exec("bash", args, false)
let SafeHiddenExec (command: string, arguments: string) =
let exitCode,stdOut,stdErr = HiddenExec(command, arguments)
if not (exitCode = 0) then
Console.Error.WriteLine(stdErr)
Console.Error.WriteLine()
Console.Error.WriteLine("Command '{0}' failed with exit code {1}. Arguments supplied: '{2}'", command, exitCode.ToString(), arguments)
Environment.Exit(1)
exitCode,stdOut,stdErr
let SafeExec (command: string, arguments: string, echo: bool) =
let exitCode = Exec(command, arguments, echo)
if not (exitCode = 0) then
Console.Error.WriteLine("Command '{0}' failed with exit code {1}. Arguments supplied: '{2}'", command, exitCode.ToString(), arguments)
Environment.Exit(1)
failwith "unreached"
()
let SafeExecBashCommand (commandWithArguments: string, echo: bool) =
let args = String.Format("-c \"{0}\"", commandWithArguments.Replace("\"", "\\\""))
if (echo) then
Console.WriteLine(commandWithArguments)
SafeExec("bash", args, false)
let FirstElementOf3Tuple (a, _, _) = a
let SecondElementOf3Tuple (_, b, _) = b
let SimpleStringSplit (str: string, separator: string): string list =
List.ofSeq(str.Split([|separator|], StringSplitOptions.RemoveEmptyEntries))
let SplitStringInLines (str: string): string list =
SimpleStringSplit(str,Environment.NewLine)
let CommandWorksInShell (command: string): bool =
let exitCode =
try
Some(FirstElementOf3Tuple(HiddenExec(command,String.Empty))
with
| :? System.ComponentModel.Win32Exception -> (); None
if exitCode.IsNone then
false
else
true
let BailIfNotSudoer(reason: string): unit =
if not (CommandWorksInShell "id") then
Console.WriteLine ("'id' unix command is needed for this script to work")
Environment.Exit(2)
()
let _,idOutput,_ = HiddenExec("id","-u")
if not (idOutput.Trim() = "0") then
Console.Error.WriteLine ("Error: needs sudo privilege. Reason: {0}", reason)
Environment.Exit(3)
()
()
let OctalPermissions (file: FileInfo): int =
let output = SecondElementOf3Tuple(SafeHiddenExec("stat", String.Format("-c \"%a\" {0}", file.FullName)))
Int32.Parse(output.Trim())
많은 솔루션이 논의되었지만 서버 재부팅 후에도 지속되는 솔루션을 찾지 못하는 것 같습니다.
서버 재부트를 통해 내 대답을 작동시키는 부분은 / etc / fstab 파일에 쓰는 것입니다.
이 솔루션의 좋은 점은 Azure, DigitalOcean, YouNameIt, ...에서 작동해야한다는 것입니다.
즐겨!