Statistics
| Branch: | Tag: | Revision:

root / src / Ganeti / HTools / Instance.hs @ 6ef49eef

History | View | Annotate | Download (12.1 kB)

1
{-| Module describing an instance.
2

    
3
The instance data type holds very few fields, the algorithm
4
intelligence is in the "Node" and "Cluster" modules.
5

    
6
-}
7

    
8
{-
9

    
10
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
11

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

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

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

    
27
-}
28

    
29
module Ganeti.HTools.Instance
30
  ( Instance(..)
31
  , Disk(..)
32
  , AssocList
33
  , List
34
  , create
35
  , isRunning
36
  , isOffline
37
  , notOffline
38
  , instanceDown
39
  , usesSecMem
40
  , applyIfOnline
41
  , setIdx
42
  , setName
43
  , setAlias
44
  , setPri
45
  , setSec
46
  , setBoth
47
  , setMovable
48
  , specOf
49
  , getTotalSpindles
50
  , instBelowISpec
51
  , instAboveISpec
52
  , instMatchesPolicy
53
  , shrinkByType
54
  , localStorageTemplates
55
  , hasSecondary
56
  , requiredNodes
57
  , allNodes
58
  , usesLocalStorage
59
  , mirrorType
60
  ) where
61

    
62
import Ganeti.BasicTypes
63
import qualified Ganeti.HTools.Types as T
64
import qualified Ganeti.HTools.Container as Container
65
import Ganeti.HTools.Nic (Nic)
66

    
67
import Ganeti.Utils
68

    
69
-- * Type declarations
70
data Disk = Disk
71
  { dskSize     :: Int       -- ^ Size in bytes
72
  , dskSpindles :: Maybe Int -- ^ Number of spindles
73
  } deriving (Show, Eq)
74

    
75
-- | The instance type.
76
data Instance = Instance
77
  { name         :: String    -- ^ The instance name
78
  , alias        :: String    -- ^ The shortened name
79
  , mem          :: Int       -- ^ Memory of the instance
80
  , dsk          :: Int       -- ^ Total disk usage of the instance
81
  , disks        :: [Disk]    -- ^ Sizes of the individual disks
82
  , vcpus        :: Int       -- ^ Number of VCPUs
83
  , runSt        :: T.InstanceStatus -- ^ Original run status
84
  , pNode        :: T.Ndx     -- ^ Original primary node
85
  , sNode        :: T.Ndx     -- ^ Original secondary node
86
  , idx          :: T.Idx     -- ^ Internal index
87
  , util         :: T.DynUtil -- ^ Dynamic resource usage
88
  , movable      :: Bool      -- ^ Can and should the instance be moved?
89
  , autoBalance  :: Bool      -- ^ Is the instance auto-balanced?
90
  , diskTemplate :: T.DiskTemplate -- ^ The disk template of the instance
91
  , spindleUse   :: Int       -- ^ The numbers of used spindles
92
  , allTags      :: [String]  -- ^ List of all instance tags
93
  , exclTags     :: [String]  -- ^ List of instance exclusion tags
94
  , arPolicy     :: T.AutoRepairPolicy -- ^ Instance's auto-repair policy
95
  , nics         :: [Nic]     -- ^ NICs of the instance
96
  } deriving (Show, Eq)
97

    
98
instance T.Element Instance where
99
  nameOf   = name
100
  idxOf    = idx
101
  setAlias = setAlias
102
  setIdx   = setIdx
103
  allNames n = [name n, alias n]
104

    
105
-- | Check if instance is running.
106
isRunning :: Instance -> Bool
107
isRunning (Instance {runSt = T.Running}) = True
108
isRunning (Instance {runSt = T.ErrorUp}) = True
109
isRunning _                              = False
110

    
111
-- | Check if instance is offline.
112
isOffline :: Instance -> Bool
113
isOffline (Instance {runSt = T.StatusOffline}) = True
114
isOffline _                                    = False
115

    
116

    
117
-- | Helper to check if the instance is not offline.
118
notOffline :: Instance -> Bool
119
notOffline = not . isOffline
120

    
121
-- | Check if instance is down.
122
instanceDown :: Instance -> Bool
123
instanceDown inst | isRunning inst = False
124
instanceDown inst | isOffline inst = False
125
instanceDown _                     = True
126

    
127
-- | Apply the function if the instance is online. Otherwise use
128
-- the initial value
129
applyIfOnline :: Instance -> (a -> a) -> a -> a
130
applyIfOnline = applyIf . notOffline
131

    
132
-- | Helper for determining whether an instance's memory needs to be
133
-- taken into account for secondary memory reservation.
134
usesSecMem :: Instance -> Bool
135
usesSecMem inst = notOffline inst && autoBalance inst
136

    
137
-- | Constant holding the local storage templates.
138
--
139
-- /Note:/ Currently Ganeti only exports node total/free disk space
140
-- for LVM-based storage; file-based storage is ignored in this model,
141
-- so even though file-based storage uses in reality disk space on the
142
-- node, in our model it won't affect it and we can't compute whether
143
-- there is enough disk space for a file-based instance. Therefore we
144
-- will treat this template as \'foreign\' storage.
145
localStorageTemplates :: [T.DiskTemplate]
146
localStorageTemplates = [ T.DTDrbd8, T.DTPlain ]
147

    
148
-- | Constant holding the movable disk templates.
149
--
150
-- This only determines the initial 'movable' state of the
151
-- instance. Further the movable state can be restricted more due to
152
-- user choices, etc.
153
movableDiskTemplates :: [T.DiskTemplate]
154
movableDiskTemplates =
155
  [ T.DTDrbd8
156
  , T.DTBlock
157
  , T.DTSharedFile
158
  , T.DTRbd
159
  , T.DTExt
160
  ]
161

    
162
-- | A simple name for the int, instance association list.
163
type AssocList = [(T.Idx, Instance)]
164

    
165
-- | A simple name for an instance map.
166
type List = Container.Container Instance
167

    
168
-- * Initialization
169

    
170
-- | Create an instance.
171
--
172
-- Some parameters are not initialized by function, and must be set
173
-- later (via 'setIdx' for example).
174
create :: String -> Int -> Int -> [Disk] -> Int -> T.InstanceStatus
175
       -> [String] -> Bool -> T.Ndx -> T.Ndx -> T.DiskTemplate -> Int
176
       -> [Nic] -> Instance
177
create name_init mem_init dsk_init disks_init vcpus_init run_init tags_init
178
       auto_balance_init pn sn dt su nics_init =
179
  Instance { name = name_init
180
           , alias = name_init
181
           , mem = mem_init
182
           , dsk = dsk_init
183
           , disks = disks_init
184
           , vcpus = vcpus_init
185
           , runSt = run_init
186
           , pNode = pn
187
           , sNode = sn
188
           , idx = -1
189
           , util = T.baseUtil
190
           , movable = supportsMoves dt
191
           , autoBalance = auto_balance_init
192
           , diskTemplate = dt
193
           , spindleUse = su
194
           , allTags = tags_init
195
           , exclTags = []
196
           , arPolicy = T.ArNotEnabled
197
           , nics = nics_init
198
           }
199

    
200
-- | Changes the index.
201
--
202
-- This is used only during the building of the data structures.
203
setIdx :: Instance -- ^ The original instance
204
       -> T.Idx    -- ^ New index
205
       -> Instance -- ^ The modified instance
206
setIdx t i = t { idx = i }
207

    
208
-- | Changes the name.
209
--
210
-- This is used only during the building of the data structures.
211
setName :: Instance -- ^ The original instance
212
        -> String   -- ^ New name
213
        -> Instance -- ^ The modified instance
214
setName t s = t { name = s, alias = s }
215

    
216
-- | Changes the alias.
217
--
218
-- This is used only during the building of the data structures.
219
setAlias :: Instance -- ^ The original instance
220
         -> String   -- ^ New alias
221
         -> Instance -- ^ The modified instance
222
setAlias t s = t { alias = s }
223

    
224
-- * Update functions
225

    
226
-- | Changes the primary node of the instance.
227
setPri :: Instance  -- ^ the original instance
228
        -> T.Ndx    -- ^ the new primary node
229
        -> Instance -- ^ the modified instance
230
setPri t p = t { pNode = p }
231

    
232
-- | Changes the secondary node of the instance.
233
setSec :: Instance  -- ^ the original instance
234
        -> T.Ndx    -- ^ the new secondary node
235
        -> Instance -- ^ the modified instance
236
setSec t s = t { sNode = s }
237

    
238
-- | Changes both nodes of the instance.
239
setBoth :: Instance  -- ^ the original instance
240
         -> T.Ndx    -- ^ new primary node index
241
         -> T.Ndx    -- ^ new secondary node index
242
         -> Instance -- ^ the modified instance
243
setBoth t p s = t { pNode = p, sNode = s }
244

    
245
-- | Sets the movable flag on an instance.
246
setMovable :: Instance -- ^ The original instance
247
           -> Bool     -- ^ New movable flag
248
           -> Instance -- ^ The modified instance
249
setMovable t m = t { movable = m }
250

    
251
-- | Try to shrink the instance based on the reason why we can't
252
-- allocate it.
253
shrinkByType :: Instance -> T.FailMode -> Result Instance
254
shrinkByType inst T.FailMem = let v = mem inst - T.unitMem
255
                              in if v < T.unitMem
256
                                 then Bad "out of memory"
257
                                 else Ok inst { mem = v }
258
shrinkByType inst T.FailDisk = let v = dsk inst - T.unitDsk
259
                               in if v < T.unitDsk
260
                                  then Bad "out of disk"
261
                                  else Ok inst { dsk = v }
262
shrinkByType inst T.FailCPU = let v = vcpus inst - T.unitCpu
263
                              in if v < T.unitCpu
264
                                 then Bad "out of vcpus"
265
                                 else Ok inst { vcpus = v }
266
shrinkByType _ f = Bad $ "Unhandled failure mode " ++ show f
267

    
268
-- | Get the number of disk spindles
269
getTotalSpindles :: Instance -> Maybe Int
270
getTotalSpindles inst =
271
  foldr (liftM2 (+) . dskSpindles ) (Just 0) (disks inst)
272

    
273
-- | Return the spec of an instance.
274
specOf :: Instance -> T.RSpec
275
specOf Instance { mem = m, dsk = d, vcpus = c } =
276
  T.RSpec { T.rspecCpu = c, T.rspecMem = m, T.rspecDsk = d }
277

    
278
-- | Checks if an instance is smaller/bigger than a given spec. Returns
279
-- OpGood for a correct spec, otherwise Bad one of the possible
280
-- failure modes.
281
instCompareISpec :: Ordering -> Instance-> T.ISpec -> T.OpResult ()
282
instCompareISpec which inst ispec
283
  | which == mem inst `compare` T.iSpecMemorySize ispec = Bad T.FailMem
284
  | which `elem` map ((`compare` T.iSpecDiskSize ispec) . dskSize)
285
    (disks inst) = Bad T.FailDisk
286
  | which == vcpus inst `compare` T.iSpecCpuCount ispec = Bad T.FailCPU
287
  | which == spindleUse inst `compare` T.iSpecSpindleUse ispec
288
    = Bad T.FailSpindles
289
  | diskTemplate inst /= T.DTDiskless &&
290
    which == length (disks inst) `compare` T.iSpecDiskCount ispec
291
    = Bad T.FailDiskCount
292
  | otherwise = Ok ()
293

    
294
-- | Checks if an instance is smaller than a given spec.
295
instBelowISpec :: Instance -> T.ISpec -> T.OpResult ()
296
instBelowISpec = instCompareISpec GT
297

    
298
-- | Checks if an instance is bigger than a given spec.
299
instAboveISpec :: Instance -> T.ISpec -> T.OpResult ()
300
instAboveISpec = instCompareISpec LT
301

    
302
-- | Checks if an instance matches a min/max specs pair
303
instMatchesMinMaxSpecs :: Instance -> T.MinMaxISpecs -> T.OpResult ()
304
instMatchesMinMaxSpecs inst minmax = do
305
  instAboveISpec inst (T.minMaxISpecsMinSpec minmax)
306
  instBelowISpec inst (T.minMaxISpecsMaxSpec minmax)
307

    
308
-- | Checks if an instance matches any specs of a policy
309
instMatchesSpecs :: Instance -> [T.MinMaxISpecs] -> T.OpResult ()
310
 -- Return Ok for no constraints, though this should never happen
311
instMatchesSpecs _ [] = Ok ()
312
instMatchesSpecs inst minmaxes =
313
  -- The initial "Bad" should be always replaced by a real result
314
  foldr eithermatch (Bad T.FailInternal) minmaxes
315
  where eithermatch mm (Bad _) = instMatchesMinMaxSpecs inst mm
316
        eithermatch _ y@(Ok ()) = y
317

    
318
-- | Checks if an instance matches a policy.
319
instMatchesPolicy :: Instance -> T.IPolicy -> T.OpResult ()
320
instMatchesPolicy inst ipol = do
321
  instMatchesSpecs inst $ T.iPolicyMinMaxISpecs ipol
322
  if diskTemplate inst `elem` T.iPolicyDiskTemplates ipol
323
    then Ok ()
324
    else Bad T.FailDisk
325

    
326
-- | Checks whether the instance uses a secondary node.
327
--
328
-- /Note:/ This should be reconciled with @'sNode' ==
329
-- 'Node.noSecondary'@.
330
hasSecondary :: Instance -> Bool
331
hasSecondary = (== T.DTDrbd8) . diskTemplate
332

    
333
-- | Computed the number of nodes for a given disk template.
334
requiredNodes :: T.DiskTemplate -> Int
335
requiredNodes T.DTDrbd8 = 2
336
requiredNodes _         = 1
337

    
338
-- | Computes all nodes of an instance.
339
allNodes :: Instance -> [T.Ndx]
340
allNodes inst = case diskTemplate inst of
341
                  T.DTDrbd8 -> [pNode inst, sNode inst]
342
                  _ -> [pNode inst]
343

    
344
-- | Checks whether a given disk template uses local storage.
345
usesLocalStorage :: Instance -> Bool
346
usesLocalStorage = (`elem` localStorageTemplates) . diskTemplate
347

    
348
-- | Checks whether a given disk template supported moves.
349
supportsMoves :: T.DiskTemplate -> Bool
350
supportsMoves = (`elem` movableDiskTemplates)
351

    
352
-- | A simple wrapper over 'T.templateMirrorType'.
353
mirrorType :: Instance -> T.MirrorType
354
mirrorType = T.templateMirrorType . diskTemplate