Statistics
| Branch: | Tag: | Revision:

root / htools / Ganeti / HTools / Program / Hcheck.hs @ 592601b3

History | View | Annotate | Download (9.7 kB)

1
{-| Cluster checker.
2

    
3
-}
4

    
5
{-
6

    
7
Copyright (C) 2012 Google Inc.
8

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

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

    
19
You should have received a copy of the GNU Gene52al Public License
20
along with this program; if not, write to the Free Software
21
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22
02110-1301, USA.
23

    
24
-}
25

    
26
module Ganeti.HTools.Program.Hcheck (main, options) where
27

    
28
import Control.Monad
29
import List (transpose)
30
import System.Exit
31
import System.IO
32
import Text.Printf (printf)
33

    
34
import qualified Ganeti.HTools.Container as Container
35
import qualified Ganeti.HTools.Cluster as Cluster
36
import qualified Ganeti.HTools.Group as Group
37
import qualified Ganeti.HTools.Node as Node
38
import qualified Ganeti.HTools.Instance as Instance
39

    
40
import qualified Ganeti.HTools.Program.Hbal as Hbal
41

    
42
import Ganeti.HTools.CLI
43
import Ganeti.HTools.ExtLoader
44
import Ganeti.HTools.Loader
45
import Ganeti.HTools.Types
46

    
47
-- | Options list and functions.
48
options :: [OptType]
49
options =
50
  [ oDataFile
51
  , oDiskMoves
52
  , oDynuFile
53
  , oEvacMode
54
  , oExInst
55
  , oExTags
56
  , oIAllocSrc
57
  , oInstMoves
58
  , oLuxiSocket
59
  , oMachineReadable
60
  , oMaxCpu
61
  , oMaxSolLength
62
  , oMinDisk
63
  , oMinGain
64
  , oMinGainLim
65
  , oMinScore
66
  , oNoSimulation
67
  , oOfflineNode
68
  , oQuiet
69
  , oRapiMaster
70
  , oSelInst
71
  , oShowHelp
72
  , oShowVer
73
  , oVerbose
74
  ]
75

    
76
-- | Check phase - are we before (initial) or after rebalance.
77
data Phase = Initial
78
           | Rebalanced
79

    
80
-- | Level of presented statistics.
81
data Level = GroupLvl
82
           | ClusterLvl
83

    
84
-- | Prefix for machine readable names
85
htcPrefix :: String
86
htcPrefix = "HCHECK"
87

    
88
-- | Phase-specific prefix for machine readable version.
89
phasePrefix :: Phase -> String
90
phasePrefix Initial = "INIT"
91
phasePrefix Rebalanced = "FINAL"
92

    
93
-- | Description of phases for human readable version.
94
phaseDescription :: Phase -> String
95
phaseDescription Initial = "initially"
96
phaseDescription Rebalanced = "after rebalancing"
97

    
98
-- | Level-specific prefix for machine readable version.
99
levelPrefix :: Level -> String
100
levelPrefix GroupLvl = "GROUP"
101
levelPrefix ClusterLvl = "CLUSTER"
102

    
103
-- | Data showed both per group and per cluster.
104
commonData :: [(String, String)]
105
commonData =[ ("N1_FAIL", "Nodes not N+1 happy")
106
            , ("CONFLICT_TAGS", "Nodes with conflicting instances")
107
            , ("OFFLINE_PRI", "Instances with primary on an offline node")
108
            , ("OFFLINE_SEC", "Instances with seondary on an offline node")
109
            ]
110

    
111
-- | Data showed per group.
112
groupData :: [(String, String)]
113
groupData = commonData ++ [("SCORE", "Group score")]
114

    
115
-- | Data showed per cluster.
116
clusterData :: [(String, String)]
117
clusterData = commonData ++
118
              [ ("NEED_REBALANCE", "Cluster is not healthy")
119
              , ("CAN_REBALANCE", "Possible to run rebalance")
120
              ]
121

    
122

    
123
-- | Format a list of key, value as a shell fragment.
124
printKeysHTC :: [(String, String)] -> IO ()
125
printKeysHTC = printKeys htcPrefix
126

    
127
-- | Prepare string from boolean value.
128
printBool :: Bool    -- ^ Whether the result should be machine readable
129
          -> Bool    -- ^ Value to be converted to string
130
          -> String
131
printBool True True = "1"
132
printBool True False = "0"
133
printBool False b = show b
134

    
135
-- | Print mapping from group idx to group uuid (only in machine readable mode).
136
printGroupsMappings :: Group.List -> IO ()
137
printGroupsMappings gl = do
138
    let extract_vals = \g -> (printf "GROUP_UUID_%d" $ Group.idx g :: String,
139
                              printf "%s" $ Group.uuid g :: String)
140
        printpairs = map extract_vals (Container.elems gl)
141
    printKeysHTC printpairs
142

    
143
-- | Print all the statistics on a group level.
144
printGroupStats :: Int -> Bool -> Phase -> Group.Group -> [Int] -> Double -> IO ()
145
printGroupStats _ True phase grp stats score = do
146
  let printstats = map (printf "%d") stats ++ [printf "%.8f" score] :: [String]
147
      printkeys = map (printf "%s_%s_%d_%s"
148
                                  (phasePrefix phase)
149
                                  (levelPrefix GroupLvl)
150
                                  (Group.idx grp))
151
                       (map fst groupData) :: [String]
152
  printKeysHTC (zip printkeys printstats)
153

    
154
printGroupStats verbose False phase grp stats score = do
155
  let printstats = map (printf "%d") stats ++ [printf "%.8f" score] :: [String]
156

    
157
  unless (verbose == 0) $ do
158
    printf "\nStatistics for group %s %s\n"
159
               (Group.name grp) (phaseDescription phase) :: IO ()
160
    mapM_ (\(a,b) -> printf "    %s: %s\n" (snd a) b :: IO ())
161
          (zip groupData printstats)
162

    
163
-- | Print all the statistics on a cluster (global) level.
164
printClusterStats :: Int -> Bool -> Phase -> [Int] -> Bool -> IO (Bool)
165
printClusterStats _ True phase stats canrebal = do
166
  let needrebal = sum stats > 0
167
      printstats = map (printf "%d") stats ++
168
                   map (printBool True) [needrebal, canrebal]
169
      printkeys = map (printf "%s_%s_%s"
170
                              (phasePrefix phase)
171
                              (levelPrefix ClusterLvl))
172
                      (map fst clusterData) :: [String]
173
  printKeysHTC (zip printkeys printstats)
174
  return needrebal
175

    
176
printClusterStats verbose False phase stats canrebal = do
177
  let needrebal = sum stats > 0
178
      printstats = map (printf "%d") stats ++
179
                   map (printBool False) [needrebal, canrebal]
180
  unless (verbose == 0) $ do
181
      printf "\nCluster statistics %s\n" (phaseDescription phase) :: IO ()
182
      mapM_ (\(a,b) -> printf "    %s: %s\n" (snd a) b :: IO ())
183
            (zip clusterData printstats)
184
  return needrebal
185

    
186
{- | Check group for N+1 hapiness, conflicts of primaries on nodes and
187
instances residing on offline nodes.
188

    
189
-}
190
perGroupChecks :: Int -> Bool -> Phase -> Group.List ->
191
                  (Gdx, (Node.List, Instance.List)) -> IO ([Int])
192
perGroupChecks verbose machineread phase gl (gidx, (nl, il)) = do
193
  let grp = Container.find gidx gl
194
      offnl = filter Node.offline (Container.elems nl)
195
      n1violated = length $ fst $ Cluster.computeBadItems nl il
196
      conflicttags = length $ filter (>0)
197
                     (map Node.conflictingPrimaries (Container.elems nl))
198
      offline_pri = sum . map length $ map Node.pList offnl
199
      offline_sec = length $ map Node.sList offnl
200
      score = Cluster.compCV nl
201
      groupstats = [ n1violated
202
                   , conflicttags
203
                   , offline_pri
204
                   , offline_sec
205
                   ]
206
  printGroupStats verbose machineread phase grp groupstats score
207
  return groupstats
208

    
209
-- | Use Hbal's iterateDepth to simulate group rebalance.
210
simulateRebalance :: Options ->
211
                     (Gdx, (Node.List, Instance.List)) ->
212
                     IO ( (Gdx, (Node.List, Instance.List)) )
213
simulateRebalance opts (gidx, (nl, il)) = do
214
  let ini_cv = Cluster.compCV nl
215
      ini_tbl = Cluster.Table nl il ini_cv []
216
      min_cv = optMinScore opts
217

    
218

    
219
  if (ini_cv < min_cv)
220
    then return (gidx, (nl, il))
221
    else do
222
      let imlen = maximum . map (length . Instance.alias) $ Container.elems il
223
          nmlen = maximum . map (length . Node.alias) $ Container.elems nl
224

    
225
      (fin_tbl, _) <- Hbal.iterateDepth False ini_tbl
226
                                        (optMaxLength opts)
227
                                        (optDiskMoves opts)
228
                                        (optInstMoves opts)
229
                                        nmlen imlen [] min_cv
230
                                        (optMinGainLim opts) (optMinGain opts)
231
                                        (optEvacMode opts)
232

    
233
      let (Cluster.Table fin_nl fin_il _ _) = fin_tbl
234
      return (gidx, (fin_nl, fin_il))
235

    
236
-- | Prints the final @OK@ marker in machine readable output.
237
printFinalHTC :: Bool -> IO ()
238
printFinalHTC = printFinal htcPrefix
239

    
240
-- | Main function.
241
main :: Options -> [String] -> IO ()
242
main opts args = do
243
  unless (null args) $ do
244
         hPutStrLn stderr "Error: this program doesn't take any arguments."
245
         exitWith $ ExitFailure 1
246

    
247
  let verbose = optVerbose opts
248
      machineread = optMachineReadable opts
249
      nosimulation = optNoSimulation opts
250

    
251
  (ClusterData gl fixed_nl ilf _ _) <- loadExternalData opts
252
  nlf <- setNodeStatus opts fixed_nl
253

    
254
  let splitinstances = Cluster.findSplitInstances nlf ilf
255
      splitcluster = Cluster.splitCluster nlf ilf
256

    
257
  when machineread $ printGroupsMappings gl
258

    
259
  groupsstats <- mapM (perGroupChecks verbose machineread Initial gl) splitcluster
260
  let clusterstats = map sum (transpose groupsstats) :: [Int]
261
      canrebalance = length splitinstances == 0
262
  needrebalance <- printClusterStats verbose machineread Initial clusterstats canrebalance
263

    
264
  when nosimulation $ do
265
    unless (verbose == 0 || machineread) $
266
      printf "Running in no-simulation mode. Exiting.\n"
267
    printFinalHTC machineread
268
    exitWith ExitSuccess
269

    
270
  when (length splitinstances > 0) $ do
271
    unless (verbose == 0 || machineread) $
272
       printf "Split instances found, simulation of re-balancing not possible\n"
273
    exitWith $ ExitFailure 1
274

    
275
  unless needrebalance $ do
276
    unless (verbose == 0 || machineread) $
277
      printf "No need to rebalance cluster, no problems found. Exiting.\n"
278
    printFinalHTC machineread
279
    exitWith ExitSuccess
280

    
281
  rebalancedcluster <- mapM (simulateRebalance opts) splitcluster
282
  newgroupstats <- mapM (perGroupChecks verbose machineread Rebalanced gl)
283
                     rebalancedcluster
284
  let newclusterstats = map sum (transpose newgroupstats) :: [Int]
285
  _ <- printClusterStats verbose machineread Rebalanced newclusterstats canrebalance
286

    
287
  printFinalHTC machineread