Statistics
| Branch: | Tag: | Revision:

root / Ganeti / HTools / CLI.hs @ 2f567ac0

History | View | Annotate | Download (12 kB)

1
{-| Implementation of command-line functions.
2

    
3
This module holds the common cli-related functions for the binaries,
4
separated into this module since Utils.hs is used in many other places
5
and this is more IO oriented.
6

    
7
-}
8

    
9
{-
10

    
11
Copyright (C) 2009 Google Inc.
12

    
13
This program is free software; you can redistribute it and/or modify
14
it under the terms of the GNU General Public License as published by
15
the Free Software Foundation; either version 2 of the License, or
16
(at your option) any later version.
17

    
18
This program is distributed in the hope that it will be useful, but
19
WITHOUT ANY WARRANTY; without even the implied warranty of
20
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21
General Public License for more details.
22

    
23
You should have received a copy of the GNU General Public License
24
along with this program; if not, write to the Free Software
25
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26
02110-1301, USA.
27

    
28
-}
29

    
30
module Ganeti.HTools.CLI
31
    ( Options(..)
32
    , OptType
33
    , parseOpts
34
    , shTemplate
35
    -- * The options
36
    , oPrintNodes
37
    , oPrintInsts
38
    , oPrintCommands
39
    , oOneline
40
    , oNoHeaders
41
    , oOutputDir
42
    , oNodeFile
43
    , oInstFile
44
    , oNodeSim
45
    , oRapiMaster
46
    , oLuxiSocket
47
    , oExecJobs
48
    , oMaxSolLength
49
    , oVerbose
50
    , oQuiet
51
    , oOfflineNode
52
    , oMinScore
53
    , oIMem
54
    , oIDisk
55
    , oIVcpus
56
    , oINodes
57
    , oMaxCpu
58
    , oMinDisk
59
    , oDiskMoves
60
    , oDynuFile
61
    , oShowVer
62
    , oShowHelp
63
    ) where
64

    
65
import Data.Maybe (fromMaybe)
66
import qualified Data.Version
67
import Monad
68
import System.Console.GetOpt
69
import System.IO
70
import System.Info
71
import System
72
import Text.Printf (printf)
73

    
74
import qualified Ganeti.HTools.Version as Version(version)
75
import Ganeti.HTools.Types
76

    
77
-- | The default value for the luxi socket
78
defaultLuxiSocket :: FilePath
79
defaultLuxiSocket = "/var/run/ganeti/socket/ganeti-master"
80

    
81
-- | Command line options structure.
82
data Options = Options
83
    { optShowNodes :: Bool           -- ^ Whether to show node status
84
    , optShowInsts :: Bool           -- ^ Whether to show the instance map
85
    , optShowCmds  :: Maybe FilePath -- ^ Whether to show the command list
86
    , optOneline   :: Bool           -- ^ Switch output to a single line
87
    , optOutPath   :: FilePath       -- ^ Path to the output directory
88
    , optNoHeaders :: Bool           -- ^ Do not show a header line
89
    , optNodeFile  :: FilePath       -- ^ Path to the nodes file
90
    , optNodeSet   :: Bool           -- ^ The nodes have been set by options
91
    , optInstFile  :: FilePath       -- ^ Path to the instances file
92
    , optInstSet   :: Bool           -- ^ The insts have been set by options
93
    , optNodeSim   :: Maybe String   -- ^ Cluster simulation mode
94
    , optMaxLength :: Int            -- ^ Stop after this many steps
95
    , optMaster    :: String         -- ^ Collect data from RAPI
96
    , optLuxi      :: Maybe FilePath -- ^ Collect data from Luxi
97
    , optExecJobs  :: Bool           -- ^ Execute the commands via Luxi
98
    , optOffline   :: [String]       -- ^ Names of offline nodes
99
    , optIMem      :: Int            -- ^ Instance memory
100
    , optIDsk      :: Int            -- ^ Instance disk
101
    , optIVCPUs    :: Int            -- ^ Instance VCPUs
102
    , optINodes    :: Int            -- ^ Nodes required for an instance
103
    , optMinScore  :: Score          -- ^ The minimum score we aim for
104
    , optMcpu      :: Double         -- ^ Max cpu ratio for nodes
105
    , optMdsk      :: Double         -- ^ Max disk usage ratio for nodes
106
    , optDiskMoves :: Bool           -- ^ Allow disk moves
107
    , optDynuFile  :: Maybe FilePath -- ^ Optional file with dynamic use data
108
    , optVerbose   :: Int            -- ^ Verbosity level
109
    , optShowVer   :: Bool           -- ^ Just show the program version
110
    , optShowHelp  :: Bool           -- ^ Just show the help
111
    } deriving Show
112

    
113
-- | Default values for the command line options.
114
defaultOptions :: Options
115
defaultOptions  = Options
116
 { optShowNodes = False
117
 , optShowInsts = False
118
 , optShowCmds  = Nothing
119
 , optOneline   = False
120
 , optNoHeaders = False
121
 , optOutPath   = "."
122
 , optNodeFile  = "nodes"
123
 , optNodeSet   = False
124
 , optInstFile  = "instances"
125
 , optInstSet   = False
126
 , optNodeSim   = Nothing
127
 , optMaxLength = -1
128
 , optMaster    = ""
129
 , optLuxi      = Nothing
130
 , optExecJobs  = False
131
 , optOffline   = []
132
 , optIMem      = 4096
133
 , optIDsk      = 102400
134
 , optIVCPUs    = 1
135
 , optINodes    = 2
136
 , optMinScore  = 1e-9
137
 , optMcpu      = -1
138
 , optMdsk      = -1
139
 , optDiskMoves = True
140
 , optDynuFile  = Nothing
141
 , optVerbose   = 1
142
 , optShowVer   = False
143
 , optShowHelp  = False
144
 }
145

    
146
-- | Abrreviation for the option type
147
type OptType = OptDescr (Options -> Result Options)
148

    
149
oPrintNodes :: OptType
150
oPrintNodes = Option "p" ["print-nodes"]
151
              (NoArg (\ opts -> Ok opts { optShowNodes = True }))
152
              "print the final node list"
153

    
154
oPrintInsts :: OptType
155
oPrintInsts = Option "" ["print-instances"]
156
              (NoArg (\ opts -> Ok opts { optShowInsts = True }))
157
              "print the final instance map"
158

    
159
oPrintCommands :: OptType
160
oPrintCommands = Option "C" ["print-commands"]
161
                 (OptArg ((\ f opts -> Ok opts { optShowCmds = Just f }) .
162
                          fromMaybe "-")
163
                  "FILE")
164
                 "print the ganeti command list for reaching the solution,\
165
                 \ if an argument is passed then write the commands to a\
166
                 \ file named as such"
167

    
168
oOneline :: OptType
169
oOneline = Option "o" ["oneline"]
170
           (NoArg (\ opts -> Ok opts { optOneline = True }))
171
           "print the ganeti command list for reaching the solution"
172

    
173
oNoHeaders :: OptType
174
oNoHeaders = Option "" ["no-headers"]
175
             (NoArg (\ opts -> Ok opts { optNoHeaders = True }))
176
             "do not show a header line"
177

    
178
oOutputDir :: OptType
179
oOutputDir = Option "d" ["output-dir"]
180
             (ReqArg (\ d opts -> Ok opts { optOutPath = d }) "PATH")
181
             "directory in which to write output files"
182

    
183
oNodeFile :: OptType
184
oNodeFile = Option "n" ["nodes"]
185
            (ReqArg (\ f o -> Ok o { optNodeFile = f,
186
                                     optNodeSet = True }) "FILE")
187
            "the node list FILE"
188

    
189
oInstFile :: OptType
190
oInstFile = Option "i" ["instances"]
191
            (ReqArg (\ f o -> Ok o { optInstFile = f,
192
                                     optInstSet = True }) "FILE")
193
            "the instance list FILE"
194

    
195
oNodeSim :: OptType
196
oNodeSim = Option "" ["simulate"]
197
            (ReqArg (\ f o -> Ok o { optNodeSim = Just f }) "SPEC")
198
            "simulate an empty cluster, given as 'num_nodes,disk,memory,cpus'"
199

    
200
oRapiMaster :: OptType
201
oRapiMaster = Option "m" ["master"]
202
              (ReqArg (\ m opts -> Ok opts { optMaster = m }) "ADDRESS")
203
              "collect data via RAPI at the given ADDRESS"
204

    
205
oLuxiSocket :: OptType
206
oLuxiSocket = Option "L" ["luxi"]
207
              (OptArg ((\ f opts -> Ok opts { optLuxi = Just f }) .
208
                       fromMaybe defaultLuxiSocket) "SOCKET")
209
              "collect data via Luxi, optionally using the given SOCKET path"
210

    
211
oExecJobs :: OptType
212
oExecJobs = Option "X" ["exec"]
213
             (NoArg (\ opts -> Ok opts { optExecJobs = True}))
214
             "execute the suggested moves via Luxi (only available when using\
215
             \ it for data gathering"
216

    
217
oVerbose :: OptType
218
oVerbose = Option "v" ["verbose"]
219
           (NoArg (\ opts -> Ok opts { optVerbose = optVerbose opts + 1 }))
220
           "increase the verbosity level"
221

    
222
oQuiet :: OptType
223
oQuiet = Option "q" ["quiet"]
224
         (NoArg (\ opts -> Ok opts { optVerbose = optVerbose opts - 1 }))
225
         "decrease the verbosity level"
226

    
227
oOfflineNode :: OptType
228
oOfflineNode = Option "O" ["offline"]
229
               (ReqArg (\ n o -> Ok o { optOffline = n:optOffline o }) "NODE")
230
               "set node as offline"
231

    
232
oMaxSolLength :: OptType
233
oMaxSolLength = Option "l" ["max-length"]
234
                (ReqArg (\ i opts -> Ok opts { optMaxLength = read i }) "N")
235
                "cap the solution at this many moves (useful for very\
236
                \ unbalanced clusters)"
237

    
238
oMinScore :: OptType
239
oMinScore = Option "e" ["min-score"]
240
            (ReqArg (\ e opts -> Ok opts { optMinScore = read e }) "EPSILON")
241
            " mininum score to aim for"
242

    
243
oIMem :: OptType
244
oIMem = Option "" ["memory"]
245
        (ReqArg (\ m opts -> Ok opts { optIMem = read m }) "MEMORY")
246
        "memory size for instances"
247

    
248
oIDisk :: OptType
249
oIDisk = Option "" ["disk"]
250
         (ReqArg (\ d opts -> Ok opts { optIDsk = read d }) "DISK")
251
         "disk size for instances"
252

    
253
oIVcpus :: OptType
254
oIVcpus = Option "" ["vcpus"]
255
          (ReqArg (\ p opts -> Ok opts { optIVCPUs = read p }) "NUM")
256
          "number of virtual cpus for instances"
257

    
258
oINodes :: OptType
259
oINodes = Option "" ["req-nodes"]
260
          (ReqArg (\ n opts -> Ok opts { optINodes = read n }) "NODES")
261
          "number of nodes for the new instances (1=plain, 2=mirrored)"
262

    
263
oMaxCpu :: OptType
264
oMaxCpu = Option "" ["max-cpu"]
265
          (ReqArg (\ n opts -> Ok opts { optMcpu = read n }) "RATIO")
266
          "maximum virtual-to-physical cpu ratio for nodes"
267

    
268
oMinDisk :: OptType
269
oMinDisk = Option "" ["min-disk"]
270
           (ReqArg (\ n opts -> Ok opts { optMdsk = read n }) "RATIO")
271
           "minimum free disk space for nodes (between 0 and 1)"
272

    
273
oDiskMoves :: OptType
274
oDiskMoves = Option "" ["no-disk-moves"]
275
             (NoArg (\ opts -> Ok opts { optDiskMoves = False}))
276
             "disallow disk moves from the list of allowed instance changes,\
277
             \ thus allowing only the 'cheap' failover/migrate operations"
278

    
279
oDynuFile :: OptType
280
oDynuFile = Option "U" ["dynu-file"]
281
            (ReqArg (\ f opts -> Ok opts { optDynuFile = Just f }) "FILE")
282
            "Import dynamic utilisation data from the given FILE"
283

    
284
oShowVer :: OptType
285
oShowVer = Option "V" ["version"]
286
           (NoArg (\ opts -> Ok opts { optShowVer = True}))
287
           "show the version of the program"
288

    
289
oShowHelp :: OptType
290
oShowHelp = Option "h" ["help"]
291
            (NoArg (\ opts -> Ok opts { optShowHelp = True}))
292
            "show help"
293

    
294
-- | Usage info
295
usageHelp :: String -> [OptType] -> String
296
usageHelp progname =
297
    usageInfo (printf "%s %s\nUsage: %s [OPTION...]"
298
               progname Version.version progname)
299

    
300
-- | Command line parser, using the 'options' structure.
301
parseOpts :: [String]               -- ^ The command line arguments
302
          -> String                 -- ^ The program name
303
          -> [OptType]              -- ^ The supported command line options
304
          -> IO (Options, [String]) -- ^ The resulting options and leftover
305
                                    -- arguments
306
parseOpts argv progname options =
307
    case getOpt Permute options argv of
308
      (o, n, []) ->
309
          do
310
            let (pr, args) = (foldM (flip id) defaultOptions o, n)
311
            po <- (case pr of
312
                     Bad msg -> do
313
                       hPutStrLn stderr "Error while parsing command\
314
                                        \line arguments:"
315
                       hPutStrLn stderr msg
316
                       exitWith $ ExitFailure 1
317
                     Ok val -> return val)
318
            when (optShowHelp po) $ do
319
              putStr $ usageHelp progname options
320
              exitWith ExitSuccess
321
            when (optShowVer po) $ do
322
              printf "%s %s\ncompiled with %s %s\nrunning on %s %s\n"
323
                     progname Version.version
324
                     compilerName (Data.Version.showVersion compilerVersion)
325
                     os arch
326
              exitWith ExitSuccess
327
            return (po, args)
328
      (_, _, errs) -> do
329
        hPutStrLn stderr $ "Command line error: "  ++ concat errs
330
        hPutStrLn stderr $ usageHelp progname options
331
        exitWith $ ExitFailure 2
332

    
333
-- | A shell script template for autogenerated scripts.
334
shTemplate :: String
335
shTemplate =
336
    printf "#!/bin/sh\n\n\
337
           \# Auto-generated script for executing cluster rebalancing\n\n\
338
           \# To stop, touch the file /tmp/stop-htools\n\n\
339
           \set -e\n\n\
340
           \check() {\n\
341
           \  if [ -f /tmp/stop-htools ]; then\n\
342
           \    echo 'Stop requested, exiting'\n\
343
           \    exit 0\n\
344
           \  fi\n\
345
           \}\n\n"