Further hlint fixes
[ganeti-local] / htools / Ganeti / HTools / Instance.hs
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 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   , AssocList
32   , List
33   , create
34   , isRunning
35   , isOffline
36   , notOffline
37   , instanceDown
38   , usesSecMem
39   , applyIfOnline
40   , setIdx
41   , setName
42   , setAlias
43   , setPri
44   , setSec
45   , setBoth
46   , setMovable
47   , specOf
48   , instBelowISpec
49   , instAboveISpec
50   , instMatchesPolicy
51   , shrinkByType
52   , localStorageTemplates
53   , hasSecondary
54   , requiredNodes
55   , allNodes
56   , usesLocalStorage
57   , mirrorType
58   ) where
59
60 import qualified Ganeti.HTools.Types as T
61 import qualified Ganeti.HTools.Container as Container
62
63 import Ganeti.HTools.Utils
64
65 -- * Type declarations
66
67 -- | The instance type.
68 data Instance = Instance
69   { name         :: String    -- ^ The instance name
70   , alias        :: String    -- ^ The shortened name
71   , mem          :: Int       -- ^ Memory of the instance
72   , dsk          :: Int       -- ^ Disk size of instance
73   , vcpus        :: Int       -- ^ Number of VCPUs
74   , runSt        :: T.InstanceStatus -- ^ Original run status
75   , pNode        :: T.Ndx     -- ^ Original primary node
76   , sNode        :: T.Ndx     -- ^ Original secondary node
77   , idx          :: T.Idx     -- ^ Internal index
78   , util         :: T.DynUtil -- ^ Dynamic resource usage
79   , movable      :: Bool      -- ^ Can and should the instance be moved?
80   , autoBalance  :: Bool      -- ^ Is the instance auto-balanced?
81   , tags         :: [String]  -- ^ List of instance tags
82   , diskTemplate :: T.DiskTemplate -- ^ The disk template of the instance
83   , spindleUse   :: Int       -- ^ The numbers of used spindles
84   } deriving (Show, Read, Eq)
85
86 instance T.Element Instance where
87   nameOf   = name
88   idxOf    = idx
89   setAlias = setAlias
90   setIdx   = setIdx
91   allNames n = [name n, alias n]
92
93 -- | Check if instance is running.
94 isRunning :: Instance -> Bool
95 isRunning (Instance {runSt = T.Running}) = True
96 isRunning (Instance {runSt = T.ErrorUp}) = True
97 isRunning _                              = False
98
99 -- | Check if instance is offline.
100 isOffline :: Instance -> Bool
101 isOffline (Instance {runSt = T.AdminOffline}) = True
102 isOffline _                                   = False
103
104
105 -- | Helper to check if the instance is not offline.
106 notOffline :: Instance -> Bool
107 notOffline = not . isOffline
108
109 -- | Check if instance is down.
110 instanceDown :: Instance -> Bool
111 instanceDown inst | isRunning inst = False
112 instanceDown inst | isOffline inst = False
113 instanceDown _                     = True
114
115 -- | Apply the function if the instance is online. Otherwise use
116 -- the initial value
117 applyIfOnline :: Instance -> (a -> a) -> a -> a
118 applyIfOnline = applyIf . notOffline
119
120 -- | Helper for determining whether an instance's memory needs to be
121 -- taken into account for secondary memory reservation.
122 usesSecMem :: Instance -> Bool
123 usesSecMem inst = notOffline inst && autoBalance inst
124
125 -- | Constant holding the local storage templates.
126 --
127 -- /Note:/ Currently Ganeti only exports node total/free disk space
128 -- for LVM-based storage; file-based storage is ignored in this model,
129 -- so even though file-based storage uses in reality disk space on the
130 -- node, in our model it won't affect it and we can't compute whether
131 -- there is enough disk space for a file-based instance. Therefore we
132 -- will treat this template as \'foreign\' storage.
133 localStorageTemplates :: [T.DiskTemplate]
134 localStorageTemplates = [ T.DTDrbd8, T.DTPlain ]
135
136 -- | Constant holding the movable disk templates.
137 --
138 -- This only determines the initial 'movable' state of the
139 -- instance. Further the movable state can be restricted more due to
140 -- user choices, etc.
141 movableDiskTemplates :: [T.DiskTemplate]
142 movableDiskTemplates =
143   [ T.DTDrbd8
144   , T.DTBlock
145   , T.DTSharedFile
146   , T.DTRbd
147   ]
148
149 -- | A simple name for the int, instance association list.
150 type AssocList = [(T.Idx, Instance)]
151
152 -- | A simple name for an instance map.
153 type List = Container.Container Instance
154
155 -- * Initialization
156
157 -- | Create an instance.
158 --
159 -- Some parameters are not initialized by function, and must be set
160 -- later (via 'setIdx' for example).
161 create :: String -> Int -> Int -> Int -> T.InstanceStatus
162        -> [String] -> Bool -> T.Ndx -> T.Ndx -> T.DiskTemplate -> Int
163        -> Instance
164 create name_init mem_init dsk_init vcpus_init run_init tags_init
165        auto_balance_init pn sn dt su =
166   Instance { name = name_init
167            , alias = name_init
168            , mem = mem_init
169            , dsk = dsk_init
170            , vcpus = vcpus_init
171            , runSt = run_init
172            , pNode = pn
173            , sNode = sn
174            , idx = -1
175            , util = T.baseUtil
176            , tags = tags_init
177            , movable = supportsMoves dt
178            , autoBalance = auto_balance_init
179            , diskTemplate = dt
180            , spindleUse = su
181            }
182
183 -- | Changes the index.
184 --
185 -- This is used only during the building of the data structures.
186 setIdx :: Instance -- ^ The original instance
187        -> T.Idx    -- ^ New index
188        -> Instance -- ^ The modified instance
189 setIdx t i = t { idx = i }
190
191 -- | Changes the name.
192 --
193 -- This is used only during the building of the data structures.
194 setName :: Instance -- ^ The original instance
195         -> String   -- ^ New name
196         -> Instance -- ^ The modified instance
197 setName t s = t { name = s, alias = s }
198
199 -- | Changes the alias.
200 --
201 -- This is used only during the building of the data structures.
202 setAlias :: Instance -- ^ The original instance
203          -> String   -- ^ New alias
204          -> Instance -- ^ The modified instance
205 setAlias t s = t { alias = s }
206
207 -- * Update functions
208
209 -- | Changes the primary node of the instance.
210 setPri :: Instance  -- ^ the original instance
211         -> T.Ndx    -- ^ the new primary node
212         -> Instance -- ^ the modified instance
213 setPri t p = t { pNode = p }
214
215 -- | Changes the secondary node of the instance.
216 setSec :: Instance  -- ^ the original instance
217         -> T.Ndx    -- ^ the new secondary node
218         -> Instance -- ^ the modified instance
219 setSec t s = t { sNode = s }
220
221 -- | Changes both nodes of the instance.
222 setBoth :: Instance  -- ^ the original instance
223          -> T.Ndx    -- ^ new primary node index
224          -> T.Ndx    -- ^ new secondary node index
225          -> Instance -- ^ the modified instance
226 setBoth t p s = t { pNode = p, sNode = s }
227
228 -- | Sets the movable flag on an instance.
229 setMovable :: Instance -- ^ The original instance
230            -> Bool     -- ^ New movable flag
231            -> Instance -- ^ The modified instance
232 setMovable t m = t { movable = m }
233
234 -- | Try to shrink the instance based on the reason why we can't
235 -- allocate it.
236 shrinkByType :: Instance -> T.FailMode -> T.Result Instance
237 shrinkByType inst T.FailMem = let v = mem inst - T.unitMem
238                               in if v < T.unitMem
239                                  then T.Bad "out of memory"
240                                  else T.Ok inst { mem = v }
241 shrinkByType inst T.FailDisk = let v = dsk inst - T.unitDsk
242                                in if v < T.unitDsk
243                                   then T.Bad "out of disk"
244                                   else T.Ok inst { dsk = v }
245 shrinkByType inst T.FailCPU = let v = vcpus inst - T.unitCpu
246                               in if v < T.unitCpu
247                                  then T.Bad "out of vcpus"
248                                  else T.Ok inst { vcpus = v }
249 shrinkByType _ f = T.Bad $ "Unhandled failure mode " ++ show f
250
251 -- | Return the spec of an instance.
252 specOf :: Instance -> T.RSpec
253 specOf Instance { mem = m, dsk = d, vcpus = c } =
254   T.RSpec { T.rspecCpu = c, T.rspecMem = m, T.rspecDsk = d }
255
256 -- | Checks if an instance is smaller than a given spec. Returns
257 -- OpGood for a correct spec, otherwise OpFail one of the possible
258 -- failure modes.
259 instBelowISpec :: Instance -> T.ISpec -> T.OpResult ()
260 instBelowISpec inst ispec
261   | mem inst > T.iSpecMemorySize ispec = T.OpFail T.FailMem
262   | dsk inst > T.iSpecDiskSize ispec   = T.OpFail T.FailDisk
263   | vcpus inst > T.iSpecCpuCount ispec = T.OpFail T.FailCPU
264   | otherwise = T.OpGood ()
265
266 -- | Checks if an instance is bigger than a given spec.
267 instAboveISpec :: Instance -> T.ISpec -> T.OpResult ()
268 instAboveISpec inst ispec
269   | mem inst < T.iSpecMemorySize ispec = T.OpFail T.FailMem
270   | dsk inst < T.iSpecDiskSize ispec   = T.OpFail T.FailDisk
271   | vcpus inst < T.iSpecCpuCount ispec = T.OpFail T.FailCPU
272   | otherwise = T.OpGood ()
273
274 -- | Checks if an instance matches a policy.
275 instMatchesPolicy :: Instance -> T.IPolicy -> T.OpResult ()
276 instMatchesPolicy inst ipol = do
277   instAboveISpec inst (T.iPolicyMinSpec ipol)
278   instBelowISpec inst (T.iPolicyMaxSpec ipol)
279   if diskTemplate inst `elem` T.iPolicyDiskTemplates ipol
280     then T.OpGood ()
281     else T.OpFail T.FailDisk
282
283 -- | Checks whether the instance uses a secondary node.
284 --
285 -- /Note:/ This should be reconciled with @'sNode' ==
286 -- 'Node.noSecondary'@.
287 hasSecondary :: Instance -> Bool
288 hasSecondary = (== T.DTDrbd8) . diskTemplate
289
290 -- | Computed the number of nodes for a given disk template.
291 requiredNodes :: T.DiskTemplate -> Int
292 requiredNodes T.DTDrbd8 = 2
293 requiredNodes _         = 1
294
295 -- | Computes all nodes of an instance.
296 allNodes :: Instance -> [T.Ndx]
297 allNodes inst = case diskTemplate inst of
298                   T.DTDrbd8 -> [pNode inst, sNode inst]
299                   _ -> [pNode inst]
300
301 -- | Checks whether a given disk template uses local storage.
302 usesLocalStorage :: Instance -> Bool
303 usesLocalStorage = (`elem` localStorageTemplates) . diskTemplate
304
305 -- | Checks whether a given disk template supported moves.
306 supportsMoves :: T.DiskTemplate -> Bool
307 supportsMoves = (`elem` movableDiskTemplates)
308
309 -- | A simple wrapper over 'T.templateMirrorType'.
310 mirrorType :: Instance -> T.MirrorType
311 mirrorType = T.templateMirrorType . diskTemplate